﻿
(function (window, undefined) {
    //    if ('XDomainRequest' in window && window.XDomainRequest !== null) {

    //        // override default jQuery transport
    //        jQuery.ajaxSettings.xhr = function () {
    //            try { return new XDomainRequest(); }
    //            catch (e) { }
    //        };

    //        // also, override the support check
    //        jQuery.support.cors = true;

    //    }
    var _coolChat = window.CoolChat,
	    core_version = "0.0.0.1",
        cookie_options = {
            expires: 7
        },
        ip_url = "getIP.aspx", // where to get user ip
	    location = window.location,
	    document = window.document,
	    docElem = document.documentElement,
	    sendsv_url = "Send.aspx", //send data url use ajax
	    revsv_url = "MsgSrv.aspx", //rev data from this url use ajax
	    window_html_url = "chatUI.htm", // chat window in html code url
	    window_css_url = "", // chat window css url   
	    CoolChat = function (option) {
	        //param option
	        //type object 
	        //option.chat : coolchat container; 
	        //option.editor: coolchat msg editor selector
	        //option.editorWidth: editor width,value type same as css property
	        //option.editorTheme: editor Theme name
	        //option.editorHeight: editor Height
	        //option.isDebug: show or hide debug info
	        return new CoolChat.fn.init(option);
	    };
    CoolChat.KEYWORD = {
        ZH_CN: {
            PLAN: "行情策略"
        },
        EN_US: {
            PLAN: "Market strategy"
        }
    };
    CoolChat.LANGUAGE = {
        ZH_CN: {
            USER_LOGOFF: "用户已下线或者不存在",
            SELECTED: "已选择",
            COUNT: "数量",
            SA: "管理员",
            WORK_SUCCESS: "操作成功",
            WORK_FAILED: "操作失败",
            DELETE_MSG_BTODAY: "删除今天之前的消息记录",
            NORMAL_MSG: "普通消息",
            EDITOR_HERE: "我的提问和回答",
            DOWNLOAD_MSGS_FAILED: "导出聊天列表失败",
            CLOSE: "关闭",
            DOWNLOAD_MSGS: "导出聊天列表",
            EDITOR_USERS: "管理用户",
            CHANGE_BG: "切换你想要的背景",
            INPUT_BG_URL: "输入背景的链接或者上传图片",
            CLICK_TO_SELECT: "点击选中此项",
            AJAX_ERROR: "网络或服务器错误",
            FAILED_UNBLOCK: "取消屏蔽消息失败,可能没有权限",
            SUCCESS_UNBLOCK: "取消屏蔽消息成功",
            SUCCESS_BLOCK: "屏蔽消息成功",
            FAILED_BLOCK: "屏蔽消息失败,可能没有权限",
            NO_RIGHT: "可能没有权限",
            ALL_BODY: "所有人",
            UN_BLOCK_MSG: "取消屏蔽",
            BLOCK_MSG: "屏蔽消息",
            YOU: "你",
            BEEN_LOGOFF: "你已被迫下线!",
            REV_ERROR: "接收消息错误,请确认互联网链接",
            PLANNER: "分析师",
            SERVER: "客服",
            GO_TO_END: "点击这里转到消息底端",
            E_ALERT_MSG_ID: "参数option.Msg_id错误",
            EMPY_MSG: "无法发送空消息",
            KEYWORD_SAIES: ":",
            SYSMSG: "系统消息",
            SILENCE: "你已经被禁言,请重试",
            E_EMPTY_MSG: "不能发送空消息",
            KEYWORD: CoolChat.KEYWORD.ZH_CN,
            ENTER_CHAT: "进入聊天室",
            OUT_CHAT: "退出聊天室",
            SENDERROR: "发送失败!",
            GUEST: "游客",
            CHAT_TO: "对",
            SAY: "说",
            CHAT_SAIES: "说:",
            KEYWORD_TO: "发布",
            SUCCESS: "成功",
            FAILED: "失败",
            CONECT: "链接",
            WELCOME: "欢迎使用",
            USERNAME: "用户名",
            PASSWORD: "密码",
            LOGIN: "登陆",
            COOLCHAT: "酷聊",
            VERSION: "版本",
            LANCODE: "ZH_CN"
        },
        US_EN: {
            UN_BLOCK_MSG: "Cancel Block",
            BLOCK_MSG: "Block Messages",
            REV_ERROR: "接收消息错误,请确认互联网链接",
            PLANNER: "分析师",
            SERVER: "客服",
            GO_TO_END: "点击这里转到消息底端",
            E_ALERT_MSG_ID: "参数option.Msg_id错误",
            EMPY_MSG: "无法发送空消息",
            KEYWORD_SAIES: ":",
            SYSMSG: "System",
            SILENCE: "你已经被禁言",
            E_EMPTY_MSG: "cant send a empty message",
            KEYWORD: CoolChat.KEYWORD.EN_US,
            ENTER_CHAT: "enter chat",
            SENDERROR: "send error!",
            GUEST: "guest",
            CHAT_TO: "to",
            CHAT_SAIES: "saies:",
            KEYWORD_TO: "publish",
            SUCCESS: "success",
            FAILED: "failed",
            CONECT: "conect",
            WELCOME: "welcome",
            USERNAME: "user name",
            PASSWORD: "pass word",
            LOGIN: "login",
            COOLCHAT: "cool chat",
            VERSION: "version",
            LANCODE: "US_EN"
        }
    };
    CoolChat.ClientAct = {
        ERROR: 0,
        MSG_SUCCESS: 1,
        MSG_FAILED: 2,
        RESET_USER: 3,
        UPDATE_USER: 4,
        REVED_MSGS: 5,
        REVED_ERROE: 6,
        LOGOFF: 7,
        USER_LIST: 8
    };
    CoolChat.USER_ROLE = {//用户角色
        GUEST: 0, //游客
        USER: 1, //用户
        SYSUSER: 2, //系统用户
        SA: 3//超级管理员
    };
    CoolChat.USER_OPTION = {
        /// <summary>
        /// 无
        /// </summary>
        NONE: -1,
        /// <summary>
        /// 获取在在线用户
        /// </summary>
        GET_ONLINE_USER: 0,
        /// <summary>
        /// 获取系统用户的类型
        /// </summary>
        GET_SYS_USER_TYPE: 1,
        /// <summary>
        /// 获取不在线用户
        /// </summary>
        GET_OFFLINE_USER: 2,
        /// <summary>
        /// 获取在线用户和系统用户(不管系统用户是否在线)
        /// </summary>
        GET_ONLINE_USER_AND_SYSUSER: 3,
        /// <summary>
        /// 禁言用户
        /// </summary>
        SILENCE_USER: 4,
        /// <summary>
        /// 取消禁言用户
        /// </summary>
        UNSILENCE_USER: 5
    };
    CoolChat.dLan = CoolChat.LANGUAGE.ZH_CN;
    CoolChat.scrollLength = 0;
    CoolChat.chats = new Array(); //保存CoolChat的实例
    CoolChat.getDate = function () {//2013-10-18 日期格式
        var date = new Date();
        var str = date.getFullYear() + "";
        str += "-" + (date.getMonth() + 1);
        str += "-" + date.getDate();
    };
    CoolChat.formatTimeString = function (date) {//"2013-10-18 15:9:51.376" 接受一个Date对象
        try {
            var str = date.getFullYear() + "";
            str += "-" + (date.getMonth() + 1);
            str += "-" + date.getDate();
            str += " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + "." + date.getMilliseconds();
            return str;
        } catch (Error) {
            return "2013-10-18 15:9:51.376";
        }
    };
    CoolChat.createDate = function (str) {//"2013-10-18 15:9:51.376"
        try {
            var d = new Date(str);
            if (isNaN(d)) {
                throw "date error";
            }
            return d;
        } catch (Error) {
            var tmp = str.split(" ", 2);
            var strDate = tmp[0].split("-", 3);
            var strTime = tmp[1].split(":", 3);
            var second = strTime[2].split(".");
            var d = new Date();
            //这里没有转换字符串成数字请注意隐患,事实上是可以使用字符串值的,如果该方法有出现问题,请留意这里
            var iMonth = parseInt(strDate[1]) - 1;
            d.setFullYear(parseInt(strDate[0]), iMonth, parseInt(strDate[2]));
            d.setHours(parseInt(strTime[0]), parseInt(strTime[1]), parseInt(second[0]), parseInt(second[1]));
            return d;
        }
    };
    CoolChat.getRootBasePath = function () {
        function _getBasePath() {
            var els = document.getElementsByTagName('script'), src;
            for (var i = 0, len = els.length; i < len; i++) {
                src = els[i].src || '';
                if (/CoolChat[\w\-\.]*\.js/.test(src)) {
                    return src.substring(0, src.lastIndexOf('/') + 1);
                }
            }
            return '';
        }
        var path = _getBasePath();
        path = path.replace("http://", "");
        path = path.substr(path.indexOf("/"));
        return path;
    };
    var rooturl = CoolChat.getRootBasePath();

    CoolChat.isVPath = function (testpath) {//对IE7以下不适用,IE7的DOC获取到的路径始终是http://开头的
        if (testpath.indexOf("http://") !== 0
                && testpath.indexOf("file://") !== 0
                && testpath.indexOf("/") !== 0
                && testpath.indexOf("https://") !== 0
                && testpath.indexOf("ftp://") !== 0
                && testpath.indexOf(":") !== 1) {
            return true;
        }
        return false;
    };
    CoolChat.SYS_USER_TYPE = {
        "-1": "",
        "0": CoolChat.dLan.ALL_BODY,
        "1": CoolChat.dLan.PLANNER,
        "2": CoolChat.dLan.SERVER,
        length: 3
    };
    CoolChat.IconSize = {
        x16: "16x16",
        x24: "24x24",
        x32: "32x32",
        x64: "64x64"
    };
    //default icon size,change it in CoolChat.init()
    CoolChat.dIconSize = CoolChat.IconSize.x16;
    CoolChat.IconUrl = function (size) {
        return new CoolChat.IconUrl.fn.init(size);
    };
    CoolChat.IconUrl.fn = CoolChat.IconUrl.prototype = {
        Error: rooturl + "imgs/" + CoolChat.dIconSize + "/delete.png",
        Success: rooturl + "imgs/" + CoolChat.dIconSize + "/accept.png",
        Info: rooturl + "imgs/" + CoolChat.dIconSize + "/info.png",
        MsgError: rooturl + "imgs/" + CoolChat.dIconSize + "/delete.png",
        MsgSuccess: rooturl + "imgs/" + CoolChat.dIconSize + "/accept.png",
        init: function (size) {//size type  CoolChat.IconSize
            this.Error = rooturl + "imgs/" + size + "/delete.png";
            this.Success = rooturl + "imgs/" + size + "/accept.png";
            this.Info = rooturl + "imgs/" + size + "/info.png";
            this.MsgError = rooturl + "imgs/" + size + "/delete.png";
            this.MsgSuccess = rooturl + "imgs/" + size + "/accept.png";
            CoolChat.dIconSize = size;
        }
    };
    CoolChat.IconUrl.fn.init.prototype = CoolChat.IconUrl.fn;
    CoolChat.AlertIcon = {
        Error: rooturl + "imgs/" + CoolChat.dIconSize + "/delete.png",
        Success: rooturl + "imgs/" + CoolChat.dIconSize + "/accept.png",
        Info: rooturl + "imgs/" + CoolChat.dIconSize + "/info.png",
        MsgError: rooturl + "imgs/" + CoolChat.dIconSize + "/delete.png",
        MsgSuccess: rooturl + "imgs/" + CoolChat.dIconSize + "/accept.png"
    };
    CoolChat.AlertOption = {
        Type: {
            error: 0, //全局用 错误 信息
            success: 1, //全局用 成功 信息
            info: 2, //全局用 信息 信息
            msgError: 3, //发送信息错误
            msgSuccess: 4 //发送信息成功
        }, //警告类型
        Position: {
            top: 0,
            foot: 1,
            msg: 2,
            broswer: 3//使用 浏览器 alert()
        },
        Icon_url: "", //string,if you want to display a icon,then put in a icon url
        //如果 没有传入icon_url,那么将会使用消息类型对应默认的icon_url
        Icon_size: CoolChat.IconSize.x24,
        Msg_id: "", //when position=msg,then apend message to $(msg_id).append()
        Show_time: 5000, //消息显示的时间 毫秒
        Flash_time: 100, //闪现时间 毫秒
        Icon_title: undefined //图标获得焦点时浮现的文字
    };
    CoolChat.MsgType = {
        SYSMSG: 0, //系统消息
        USERMSG: 1, //用户消息
        SYSUSERMSG: 2, //系统用户消息
        SAMSG: 3, //超级管理员消息
        GUESTMSG: 4, //游客消息
        KEYWORD: 5//关键字消息,无接收者
    };
    CoolChat.HTML_CODE = [

        ];
    CoolChat.guid = 0;
    CoolChat.UserListAct = {
        NONE: -1,
        FIXED: 0, //FIXED 填充用户列表,如果指示了startFixedOnlineUserList; 
        OFFLINE: 1 //OFFLINE 缓存在服务器中已下线的用户列表
    };
    CoolChat.UserListData = {//返回了用户数组,并且指示如何操作该数组
        Act: CoolChat.UserListAct.FIXED,
        List: [] //用户数组
    };
    CoolChat.RadioGroup = function (selector, items, checkedClass, normalClass, hoverClass, defaultItem, valueHolder, allowNoSelect) {
        return new CoolChat.RadioGroup.fn.init(selector, items, checkedClass, normalClass, hoverClass, defaultItem, valueHolder, allowNoSelect);
    };
    CoolChat.RadioGroup.fn = CoolChat.RadioGroup.prototype = {
        //        SelectItem: undefined,
        //        SelectIndex: -1,
        //        SelectValue: undefined,
        Selector: undefined,
        ValueHolder: undefined,
        CheckedClass: undefined,
        NormalClass: undefined,
        DefaultItem: undefined,
        ValueHolder: undefined,
        AllowNoSelect: false, //设置为TURE则表示可以无选中项
        init: function (selector, items, checkedClass, normalClass, hoverClass, defaultItem, valueHolder, allowNoSelect) {
            //构造此类时,请确保项的DOM元素都已经加载完毕,若未加载完毕,将导致错误
            //在构造时如果传入默认顶(defaultItem),就会立即设置默认项,那么在构造之后绑定的事件则得不到调用.
            //如果需要构造时调用事件,那么在构造时不要传入默认值,在绑定事件方法之后,再设置一个已选中项
            //selecttor(必选): 选择器,选择哪些元素做为RadioButton; 
            //items(必选): 项的数组,用于初始化绑定项的索引请与在元素中的索引一致,
            //      key value objects,example: [{ Key: '男',Value: 0},{Key:'女',Value:1}]; 
            //checkedClass(必选):选中时的类,用于定义样式; 
            //normalClass(必选): ;
            //hoverClass: 可选,如果没有指定将使用checkedClass;
            //defaultItem: 默认选中的项,可以是数组索引,或者是选择器,或者是对象,如果都没有,那么默认选中第一个.
            //valueHolder: 选择器,如果有的话其HTML将会被设置为this.SelectValue.toString()的值
            //allowNoSelect: 是否允许无选中项
            var _this = this;
            var currentJQ = undefined; //设置当前选中项
            var itemLength = 0;
            var Handlers = [],
            Handle = {
                type: undefined,
                fn: undefined
            },
            HandleType = {
                changing: "changing",
                changed: "changed",
                adding: "adding",
                removing: "removing",
                added: "added",
                removed: "removed"
            };
            this.Selector = selector;
            var a = $(selector);
            if (a.length === 0 && items.length !== 0) {
                throw Error("there no item in DOM");
            }
            if (a.length !== items.length) {
                throw Error("dom length not eq item length");
            }
            itemLength = a.length;
            this.ValueHolder = valueHolder;
            this.AllowNoSelect = allowNoSelect === true;
            if (!hoverClass) {
                hoverClass = checkedClass;
            }
            this.CheckedClass = checkedClass;
            this.NormalClass = normalClass;
            this.DefaultItem = defaultItem;
            this.ValueHolder = valueHolder;
            function _doIngEvent(citem, cindex, type) {
                var notgo = false;
                for (var x in Handlers) {
                    var h = Handlers[x];
                    if (h.type === type) {
                        var r = h.fn(citem, cindex, notgo);
                        if (r === false) {
                            notgo = true;
                        }
                    }
                }
                return notgo;
            }
            function _doEdEvent(citem, cindex, type) {
                for (var x in Handlers) {
                    var h = Handlers[x];
                    if (h.type === type) {
                        h.fn(citem, cindex);
                    }
                }
            }
            function _doAdding(citem, cindex) {
                return _doIngEvent(citem, cindex, HandleType.adding);
            }
            function _doRemoving(citem, cindex) {
                return _doIngEvent(citem, cindex, HandleType.removing);
            }
            function _doAdded(citem, cindex) {
                _doEdEvent(citem, cindex, HandleType.added);
            }
            function _doRemoved(citem, cindex) {
                _doEdEvent(citem, cindex, HandleType.removed);
            }
            function _doChanging(citem, cindex) {//返回true 中止值的改变
                return _doIngEvent(citem, cindex, HandleType.changing);
            }
            function _doChanged(citem, cindex) {
                _doEdEvent(citem, cindex, HandleType.changed);
            }
            a.each(function (i) {//绑定项到DOM中
                $(this).data("Item", items[i]);
            });
            a.data("notselect", true);
            function ItemClick() {
                var clickItem = $(this).data("Item");
                a = $(_this.Selector); //重新获取过所有项,防止项有变更
                var clickIndex = a.index(this);
                //clickItem.Index = clickIndex; //将选中项的索引记录在Item中,在事件中可用
                if ($(this).data("notselect")) {//设置为选中
                    if (_doChanging(clickItem, clickIndex)) {
                        return;
                    }
                    if (currentJQ) {//如果有当前选择项的JQuery对象,清除选中状态
                        currentJQ.removeClass(checkedClass).addClass(normalClass);
                        currentJQ.data("notselect", true);
                    }
                    $(this).removeClass(normalClass).addClass(checkedClass);
                    currentJQ = $(this); //设置当前选中项
                    $(this).data("notselect", false); //表示为选中项
                    _this.setHolderValue();
                    _doChanged(clickItem, clickIndex);
                }
                else {//点击了选中项
                    if (_this.AllowNoSelect) {//可以无选中项
                        _this.check(false); //清除选中项
                    }
                }
            }
            function ItemHoverIn() {//in
                var _class = $(this).data("notselect") ? normalClass : checkedClass;
                $(this).removeClass(_class).addClass(hoverClass);
            }
            function ItemHoverOut() {//out
                var _class = $(this).data("notselect") ? normalClass : checkedClass;
                $(this).removeClass(hoverClass).addClass(_class);
            }
            this.getLength = function () {
                return itemLength;
            };
            this.getSelectItem = function () {
                if (currentJQ) {
                    return currentJQ.data("Item");
                }
                return undefined;
            };
            this.getSelectIndex = function () {
                if (currentJQ) {
                    return $(this.Selector).index(currentJQ[0]);
                }
                return -1;
            };
            this.getSelectValue = function () {
                if (currentJQ) {
                    return currentJQ.data("Item").Value;
                }
                return undefined;
            };
            this.clearSelect = function () {
                _doChanging(undefined, -1);
                a.data("notselect", true);
                a.removeClass(this.CheckedClass).addClass(this.NormalClass);
                currentJQ = undefined; //设定当前选定项
                this.setHolderValue();
                _doChanged(undefined, -1);
            };
            this.check = function (i) {
                //i:可以是数组索引, 或者是选择器,是否, 或者是对象,undefined 清除选中状态
                //设置成功返回true,失败返回false
                var sel0 = false;
                switch (typeof i) {
                    case "number": //it's an index of Items
                        this.getJqItem(i).click();
                        sel0 = this.getJqItem(i).length > 0;
                        break;
                    case "string":
                        $(i).click(); //it's a selector
                        sel0 = $(i).length > 0;
                        break;
                    case "object": //it's a {Key: ,Value: } Object
                        var checkItem = this.getJqItem(i);
                        checkItem.click();
                        sel0 = checkItem.length > 0;
                        break;
                    case "boolean": //value = true set the this.items[0] for the default check,false,set all items to unchecked
                        var a = $(this.Selector);
                        if (i === true) {
                            this.getJqItem(0).click();
                            sel0 = true;
                        }
                        else {
                            this.clearSelect();
                        }
                        break;
                    case "undefined":
                        this.clearSelect();
                        break;
                }
                return sel0;
            };
            function _setCtrl() {
                a.click(ItemClick);
                a.hover(ItemHoverIn, ItemHoverOut);
                _this.check(defaultItem);
            }
            _setCtrl();
            this.changing = function (fn) {//选中项改变前调用
                //fn(item,i,cancel)
                //item: 将要选择的顶{Key:"",Value:"",Index:0}
                //i: 将要选择的索引
                //cancel: 为true 则指示值的改变已经被取消
                //fn 返回 false 结束值的改变
                this.bind(fn, HandleType.changing);
            };
            this.changed = function (fn) {//选中项改变后调用
                //fn(item)
                //item: 已经选择的项{Key:"",Value:"",Index:0}
                //fn(item,i)
                //item: 已经选择的顶{Key:"",Value:"",Index:0}
                //i: 已经选择的索引
                this.bind(fn, HandleType.changed);
            };
            this.adding = function (fn) {
                this.bind(fn, HandleType.adding);
            };
            this.removing = function (fn) {
                this.bind(fn, HandleType.removing);
            };
            this.added = function (fn) {
                this.bind(fn, HandleType.added);
            };
            this.removed = function (fn) {
                this.bind(fn, HandleType.removed);
            };
            this.bind = function (fn, t) {
                fn.guid = CoolChat.guid++;
                Handlers.push({ type: t, fn: fn });
            };
            this.unbind = function (fn, t) {
                //如果fn 和 t 都不存在,那么清除所有事件绑定
                //如果fn 为 事件类型,那么就清除所有该类型的事件绑定
                if (typeof fn === "function" && !t) {//fn 为方法,并且t不存在
                    for (var x in Handlers) {
                        var h = Handlers[x];
                        if (h.fn.guid === fn.guid) {
                            Handlers.splice(x, 1);
                            break;
                        }
                    }
                    return;
                }
                if (typeof fn === "function" && t) {//fn 为方法,并且t为类型
                    for (var x in Handlers) {
                        var h = Handlers[x];
                        if (h.type === t && h.fn.guid === fn.guid) {
                            Handlers.splice(x, 1);
                            break;
                        }
                    }
                    return;
                }
                switch (fn) {//看看是否为事件类型
                    case HandleType.changed:
                        for (var x in Handlers) {
                            var h = Handlers[x];
                            if (h.type === HandleType.changed) {
                                Handlers.splice(x, 1);
                                continue;
                            }
                        }
                        return;
                    case HandleType.changing:
                        for (var x in Handlers) {
                            var h = Handlers[x];
                            if (h.type === HandleType.changing) {
                                Handlers.splice(x, 1);
                                continue;
                            }
                        }
                        return;
                }
                if (!fn && !t) {//两个参数都没有,全部清除
                    Handlers.length = 0;
                    return;
                }
            };

            this.addItem = function (item, selector) {
                //请于DOM元素添加完成时再添加项
                //item: an item object
                //selector: 对于该项的选择器,用于添加事件,请确定此选择器只选择到该项元素
                //需要对添加的项绑定事件
                var JQi = $(selector);
                var index = $(_this.Selector).index(JQi);
                if (JQi.length == 0) {
                    throw Error("selector error");
                }
                if (_doAdding(item, index)) {
                    return;
                }
                JQi.data("Item", item);
                JQi.data("notselect", true);
                JQi.click(ItemClick);
                JQi.hover(ItemHoverIn, ItemHoverOut);
                itemLength++;
                _doAdded(item, index);
            };
            this.removeItem = function (i, iskey) {//i : can be an Item Object or index; iskey: if iskey===true,then i is a key of item
                var item = this.getJqItem(i, iskey);
                var index = $(_this.Selector).index(item);
                var datai = item.data("Item");
                datai.isSelected = item.data("notselect") === false;
                if (_doRemoving(datai, index)) {
                    return;
                }
                if (datai.isSelected) {//如果为选中项,
                    this.check(this.DefaultItem); //选择默认项
                }
                item.remove();
                itemLength--;
                _doRemoved(datai, index);
            }
        },
        setHolderValue: function () {
            var _v = this.getSelectValue();
            if (!_v) {
                $(this.ValueHolder).html("");
            }
            else if (typeof _v === "object") {
                _v = $.stringifyJSON(_v);
                $(this.ValueHolder).html(_v);
            } else {
                _v = _v.toString();
                $(this.ValueHolder).html(_v);
            }
        },
        getItems: function () {
            var items = [];
            $(this.Selector).each(function (index) {
                items.push($(this).data("Item"));
            });
            return items;
        },
        getJqItem: function (i, iskey) {//i可以是 索引,也可以是item
            var j = $(undefined);
            var itype = $.type(i);
            if (iskey === true) {//i is a key
                $(this.Selector).each(function (index) {
                    var item = $(this).data("Item");
                    if (item.Key === i) {
                        j = $(this);
                        return false;
                    }
                });
            } else if (itype === "number") {
                j = $(this.Selector).eq(i);
            } else if (itype === "object") {
                $(this.Selector).each(function (_i) {
                    var item = $(this).data("Item");
                    if (item.Key === i.Key && item.Value === i.Value) {
                        j = $(this);
                        return false;
                    }
                });
            }
            return j;
        }
    };
    CoolChat.RadioGroup.fn.init.prototype = CoolChat.RadioGroup.fn;
    CoolChat.Dailog = function (content, size) {
        return new CoolChat.Dailog.fn.init(content, size);
    };
    CoolChat.Dailog.fn = CoolChat.Dailog.prototype = {
        Content: undefined, //窗口的内容,HTML组成
        Size: { W: 400, H: 300 }, //大小,默认是宽:400,高300,单位像素
        Item: undefined,
        ItemUrl: "CoolChatDailogItem.htm",
        DailogID: undefined,
        DailogContentID: undefined,
        DailogStaticID: undefined,
        EfectSpeed: 200,
        init: function (content, size) {
            //content 内容必须,size 可选,未输入size,使用默认,或者后面调用方法设置过
            //Dailog new 完后,请自己添加对Dailog内容的控制事件,然后再调用Show
            var _this = this;
            $.ajax({//get item html
                url: CoolChat.getRootBasePath() + _this.ItemUrl,
                type: "GET",
                cache: false,
                async: false,
                success: function (data, textStatus, jqXHR) {
                    _this.Item = data;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _this.Item = '    <div class="static-none-other-option">'
+ '    </div>'
+ '    <div class="dialog-holder-container">'
+ '        <div class="dailog-holder-v"></div>'
+ '        <div class="dailog-holder">'
+ '            <div class="dailog-header"><div class="dailog-close"><img src="imgs/16x16/delete.png" /></div></div>'
+ '            <div class="dailog-content">'
+ '            </div>'
+ '            <div class="dailog-foot"></div>'
+ '        </div>'
+ '    </div>';
                }
            });
            this.Item = $(this.Item);
            function changeRootPath() {
                var imgsrc = $(this).attr("src");
                if (!imgsrc) {
                    return;
                }
                if ($.browser.msie && parseFloat($.browser.version) < 8) {
                    //为MSIE版本小于8的浏览器做兼容
                    var tmpurl = document.URL;
                    tmpurl = tmpurl.split("?")[0];
                    tmpurl = tmpurl.substr(0, tmpurl.lastIndexOf("/") + 1);
                    imgsrc = imgsrc.replace(tmpurl, "");
                }
                if (CoolChat.isVPath(imgsrc.toLowerCase())) {
                    //这是一个虚拟路径,更新为绝对路径
                    $(this).attr("src", _this.rootBasePath + imgsrc);
                }

            }
            this.Item.each(changeRootPath);
            var container = this.Item.filter(".dialog-holder-container");
            this.DailogID = container.attr("id", "dialog-holder-container-" + (CoolChat.guid++)).attr("id");
            this.DailogStaticID = this.Item.filter(".static-none-other-option").attr("id", "static-none-other-option-" + (CoolChat.guid++)).attr("id");
            this.DailogContentID = container.find(".dailog-content").attr("id", "dailog-content-" + (CoolChat.guid++)).attr("id");
            this.Item.filter(".static-none-other-option").css("z-index", CoolChat.guid++);
            container.css("z-index", CoolChat.guid++);
            container.find(".dailog-close").attr("title", CoolChat.dLan.CLOSE);
            container.find(".dailog-close").click(function () {
                _this.close();
            });
            if (content) {
                container.find(".dailog-content").html("");
                container.find(".dailog-content").append(content);
                this.Content = content;
            }
            $("body").append(this.Item);
            if (size) {
                this.size(size);
            } else {
                this.size(this.Size);
            }
        },
        content: function (c) {
            $("#" + this.DailogID + " .dailog-content").html("");
            $("#" + this.DailogID + " .dailog-content").append(c);
        },
        size: function (size) {//设置窗口的大小
            $("#" + this.DailogID + " .dailog-holder-v").css("margin-bottom", "-" + (size.H / 2) + "px");
            $("#" + this.DailogID + " .dailog-holder").css("width", size.W);
            $("#" + this.DailogID + " .dailog-holder").css("height", size.H);
        },
        show: function () {//用于显示窗口
            $("#" + this.DailogStaticID).fadeIn(this.EfectSpeed);
            $("#" + this.DailogID).fadeIn(this.EfectSpeed);
        },
        hide: function () {//用于关闭窗口
            $("#" + this.DailogID).fadeOut(this.EfectSpeed);
            $("#" + this.DailogStaticID).fadeOut(this.EfectSpeed);
        },
        close: function () {
            $("#" + this.DailogID).fadeOut(this.EfectSpeed);
            $("#" + this.DailogStaticID).fadeOut(this.EfectSpeed);
            $("#" + this.DailogID).remove();
            $("#" + this.DailogStaticID).remove();
        }
    };
    CoolChat.Dailog.fn.init.prototype = CoolChat.Dailog.fn;
    CoolChat.Message = function () {
        return new CoolChat.Message.fn.init();
    };
    CoolChat.Message.fn = CoolChat.Message.prototype = {
        init: function () {
        },
        Id: -1, //消息ID
        From: null, //发送者 object CoolChat.User
        To: null, //接收者 object CoolChat.User
        Keyword: "", //系统关键字,如 行情策略
        Type: CoolChat.MsgType.GUESTMSG, //消息类型,如果类型为 CoolChat.MsgType.KEYWORD,那么该消息无接收者 接收者处将显示 keyword 内容
        Content: "",
        Addtime: CoolChat.formatTimeString(new Date()),
        MsgID: "", //由用户ID和消息时间的MD5生成
        MsgTime: CoolChat.formatTimeString(new Date()) //发送时间
    };
    CoolChat.Message.fn.init.prototype = CoolChat.Message.fn;
    CoolChat.User = function (un, sid, uid, urole, uip, silence) {
        if (!un && !sid && !uid && urole && uip && silence)
            return new CoolChat.User.fn.init();
        else
            return new CoolChat.User.fn.initParam(un, sid, uid, urole, uip, silence);
    };
    CoolChat.User.fn = CoolChat.User.prototype = {
        Id: -1,
        Avatar: undefined, //头像
        UserName: null,
        SessionId: null,
        UserID: null, //用户ID,游客的用户ID由IP的MD5组成
        UserIP: null,
        UserRole: CoolChat.USER_ROLE.GUEST,
        SysUserType: -1, //用户Role为系统用户时,该属性指示系统用户类型
        SilenceExpires: CoolChat.formatTimeString(new Date()), // 禁言,时间类型,如果设置了该值在该时间内该用户禁止发言,未设置的值为null
        LastLoginTime: CoolChat.formatTimeString(new Date()), //最后活动时间
        AddTime: CoolChat.formatTimeString(new Date()), //用户创建时间
        IsOnline: false, //管理员使用此字段标识是否在线
        init: function () {
        },
        initParam: function (un, sid, uid, urole, uip, silence) {
            this.UserName = un;
            this.SessionId = sid;
            this.UserID = uid;
            this.UserRole = urole;
            this.UserIP = uip;
            this.SilenceExpires = silence;
        },
        copyTo: function (user) {
            user.Id = this.Id;
            user.UserName = this.UserName;
            user.SessionId = this.SessionId;
            user.UserID = this.UserID;
            user.UserIP = this.UserIP;
            user.UserRole = this.UserRole;
            user.SysUserType = this.SysUserType;
            user.SilenceExpires = this.SilenceExpires;
            user.LastLoginTime = this.LastLoginTime;
            user.AddTime = this.AddTime;
            user.IsOnline = this.IsOnline;
        }
    };
    CoolChat.User.fn.init.prototype = CoolChat.User.fn;
    CoolChat.User.fn.initParam.prototype = CoolChat.User.fn;
    CoolChat.fn = CoolChat.prototype = {
        index: -1, //此实例在CoolChat.chats 中的索引
        coolChat: core_version,
        user: new CoolChat.User(),
        ip_json_url: ip_url,
        constructor: CoolChat,
        sendsv_url: sendsv_url,
        revsv_url: revsv_url,
        MsgSoundURL: "msg.mp3",
        fixedUserList: false, //为TRUE时 接收消息总返回用户列表
        CountHolder: undefined, //设置在线用户数量的元素选择器
        isRevMsgs: false, //接收消息,如果false就不接收
        isDebug: false, //是否显示调试信息
        showMsgSuccess: false, // 显示消息成功提示
        todayMsgsUrl: "today.aspx",
        window_html_url: window_html_url,
        window_css_url: window_css_url,
        eidtor_html_url: "ChatEditorItem.htm",
        userMsgItemUrl: "UserMsgItem.htm",
        sysMsgItemUrl: "SysMsgItem.htm",
        sysUserMsgItemUrl: "SysUserMsgItem.htm",
        keyWordMsgItemUrl: "KeyWordMsgItem.htm",
        userMsgItemText: '<li id="@msg_id"><span class="coolchat-chat-msg-id">@msg_id</span><span class="coolchat-chat-content-holder-user-fromer">@FromUserName</span><span class="coolchat-chat-content-holder-to">@CHAT_TO</span><span class="coolchat-chat-content-holder-sysuser-saver">@ToUserName</span><span class="coolchat-chat-content-holder-saies">@CHAT_SAIES</span><span class="coolchat-chat-content-holder-saywhat">@MsgContent</span></li>',
        sysMsgItemText: '<li id="@msg_id"><span class="coolchat-chat-msg-id">@msg_id</span><span class="coolchat-chat-content-holder-user-fromer-sysmsg">@SYSMSG</span><span class="coolchat-chat-content-holder-saies">@CHAT_SAIES</span><span class="coolchat-chat-content-holder-saywhat"><span class="coolchat-chat-content-holder-user-fromer">@ToUserName</span><span class="coolchat-chat-content-holder-user-fromer-sysmsg-holder">@MsgContent</span></span></li>',
        sysUserMsgItemText: '<li id="@msg_id"><span class="coolchat-chat-msg-id">@msg_id</span>  <span class="coolchat-chat-content-holder-sysuser-fromer">@SysUserType-@FromUserName</span><span class="coolchat-chat-content-holder-to">@CHAT_TO</span><span class="coolchat-chat-content-holder-user-saver">@ToUserName</span><span class="coolchat-chat-content-holder-saies">@CHAT_SAIES</span><span class="coolchat-chat-content-holder-saywhat">@MsgContent</span></li>',
        keyWordMsgItemText: '<li id="@msg_id"><span class="coolchat-chat-msg-id">@msg_id</span><span class="coolchat-chat-content-holder-sysuser-fromer">@FromUserName</span><span class="coolchat-chat-content-holder-to">@KEYWORD_TO</span><span class="coolchat-chat-content-holder-keyword">@KEYWORD</span><span class="coolchat-chat-content-holder-saies">@KEYWORD_SAIES</span><span class="coolchat-chat-content-holder-saywhat">@MsgContent</span></li>',
        UserListItemText: {
            Online: undefined,
            Offline: undefined,
            OnlineBlock: undefined,
            OfflineBlock: undefined
        },
        UserListItemUrl: {
            Online: "OnlineUserItem.htm",
            Offline: "OfflineUserItem.htm",
            OnlineBlock: "OnlineUserBlockItem.htm",
            OfflineBlock: "OfflineUserBlockItem.htm"
        },
        editor: ".coolchat-chat-editor-holder-textarea",
        editor_container: undefined,
        chat: "", //no chat container
        container: null,
        radioTo: undefined,
        userRadio: undefined,
        length: 0,
        revtick: 1000, //接收消息的间隔,毫秒单位
        revTimeOut: 1000, //接收消息的超时时间,毫秒单位
        revtimerID: null, //重复调用时返回的ID,setInterve
        revJQHR: null, //接收消息时的JQHR对象
        sendJQHR: null,
        userListTick: 10000, //获取多少时间内活动的用户,毫秒单位
        msgMaxItem: 1000, //显示消息最多条数
        _this: null,
        basePath: null,
        rootBasePath: null,
        virtualCount: 0,
        init: function (option) {
            this.chat = option.chat;
            this.isDebug = option.isDebug === true;
            this.showMsgSuccess = option.showMsgSuccess === true;
            this._this = this;
            var _this = this; //用一个局部变量来解决该方法内部方法访问 CoolChat 的 this 
            this.index = CoolChat.chats.length;
            CoolChat.chats.push(this);

            function _getBasePath() {
                //获取基本的路径,如果是IE7以下的浏览器,则获取到引用本<script>的src值
                //所以为了兼容所有浏览器,在引用脚本时请使用绝对路径
                var els = document.getElementsByTagName('script'), src;
                for (var i = 0, len = els.length; i < len; i++) {
                    src = els[i].src || '';
                    if (/CoolChat[\w\-\.]*\.js/.test(src)) {
                        return src.substring(0, src.lastIndexOf('/') + 1);
                    }
                }
                return '';
            }
            function _getRootBasePath() {
                var path = _getBasePath();
                path = path.replace("http://", "");
                path = path.substr(path.indexOf("/"));
                return path;
            }
            this.basePath = _getBasePath();
            this.rootBasePath = _getRootBasePath();
            this.ip_json_url = this.rootBasePath + this.ip_json_url;
            this.sendsv_url = this.rootBasePath + this.sendsv_url;
            this.revsv_url = this.rootBasePath + this.revsv_url;
            this.window_html_url = this.rootBasePath + this.window_html_url;
            this.window_css_url = this.rootBasePath + this.window_css_url;
            this.eidtor_html_url = this.rootBasePath + this.eidtor_html_url;
            this.userMsgItemUrl = this.rootBasePath + this.userMsgItemUrl;
            this.sysMsgItemUrl = this.rootBasePath + this.sysMsgItemUrl;
            this.sysUserMsgItemUrl = this.rootBasePath + this.sysUserMsgItemUrl;
            this.keyWordMsgItemUrl = this.rootBasePath + this.keyWordMsgItemUrl;
            this.UserListItemUrl.Online = this.rootBasePath + this.UserListItemUrl.Online;
            this.UserListItemUrl.Offline = this.rootBasePath + this.UserListItemUrl.Offline;
            this.UserListItemUrl.OnlineBlock = this.rootBasePath + this.UserListItemUrl.OnlineBlock;
            this.UserListItemUrl.OfflineBlock = this.rootBasePath + this.UserListItemUrl.OfflineBlock;
            this.todayMsgsUrl = this.rootBasePath + this.todayMsgsUrl;
            ////////////////////////////////////////start init chat window///////////////////////////////////////////////////

            var window_html;
            $.ajax({
                url: _this.window_html_url,
                async: false,
                type: "GET",
                cache: false,
                success: function (data, textStatus, jqXHR) {
                    window_html = data;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    window_html = '<div class="coolchat-chat-container">'
+ '                <div id="debug_msg_holder" style="position:fixed; top: 0; left: 0; width: 100%; margin: 0 auto;">debug</div>'
+ '                <div class="coolchat-chat-content">'
+ '                    <div class="coolchat-chat-content-alert-title">'
+ '                        <div class="coolchat-chat-content-alert">   '
+ '                            <div class="coolchat-chat-content-alert-text"><!--头部消息提示内容 -->'
+ '                                <img class="coolchat-chat-content-alert-icon" src="imgs/24x24/info.png" alt="info" title="icon"/><!--头部消息提示图片 使用 CSS backgroud-image 设置 -->'
+ '                                <span class="coolchat-chat-content-alert-text-holder">这边输入消息文字</span>'
+ '                            </div>'
+ '                        </div>'
+ '                    </div>'
+ '                    <div class="clear">&nbsp;</div>'
+ '                    <div class="coolchat-chat-content-holder">'
+ '                        <ul>'
+ '                        </ul>'
+ '                        <div class="coolchat-chat-content-holder-msg-preview"></div>'
+ '                    </div>'
+ '                    <div class="coolchat-chat-content-alert-foot">                        '
+ '                        <div class="coolchat-chat-content-alert-foot-text">'
+ '                        <img class="coolchat-chat-content-alert-foot-icon" src="imgs/24x24/info.png" alt="info" title="icon"/>'
+ '                        <!--尾部消息提示内容 --><span class="coolchat-chat-content-alert-foot-text-holder">这边输入消息文字</span>                         '
+ '                        </div>'
+ '                        <div class="coolchat-chat-content-alert-gotoend"><a href="javascript:void(0);"></a></div>                        '
+ '                    </div>'
+ '                </div>'
+ '            </div>';
                }
            });
            _this.container = $("body");
            if (!option.chat) {// HANDLE: $(""), $(null), $(undefined), $(false)
                //以body 对象为容器,将先清除body内容,再生成聊天室窗口
                _this.container = $("body");
                option.chat = "body";
                //生成聊天室代码
            } else {
                _this.container = $(option.chat);
                if (_this.container.length > 1) {//超过一个,使用第一个
                    _this.container = _this.container.first();
                }
                if (_this.container.length == 0) {//如果没有获取到
                    _this.container = $("body");
                }
            }
            function changeRootPath() {
                var imgsrc = $(this).attr("src");
                if (!imgsrc) {
                    return;
                }
                if ($.browser.msie && parseFloat($.browser.version) < 8) {
                    //为MSIE版本小于8的浏览器做兼容
                    var tmpurl = document.URL;
                    tmpurl = tmpurl.split("?")[0];
                    tmpurl = tmpurl.substr(0, tmpurl.lastIndexOf("/") + 1);
                    imgsrc = imgsrc.replace(tmpurl, "");
                }
                if (CoolChat.isVPath(imgsrc.toLowerCase())) {
                    //这是一个虚拟路径,更新为绝对路径
                    $(this).attr("src", _this.rootBasePath + imgsrc);
                }

            }
            var jqwindow = $(window_html);
            jqwindow.find("img").each(changeRootPath);
            this.container.append(jqwindow);
            var editor_html;
            $.ajax({
                url: _this.eidtor_html_url,
                async: false,
                type: "GET",
                cache: false,
                success: function (data, textStatus, jqXHR) {
                    editor_html = data;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    editor_html = '<div class="coolchat-chat-editor">'
                        + '<div class="coolchat-chat-editor-holder">'
                            + '<textarea class="coolchat-chat-editor-holder-textarea" rows="0" cols="0" id="coolchat-chat-editor-content"></textarea>'
                        + '</div>'
                        + '<div class="coolchat-chat-editor-toolbar">'
                            + '<div class="coolchat-radio-buttons">'
                                + '<span style="display:none">1</span><!--这个SPAN存入下面项 点击时的对应的CoolChat.SYS_USER_TYPE索引'
                                + '<a id="coolchat-chat-editor-to-sysuser" class="coolchat-chat-editor-to" href="javascript:void(0);">对分析师说</a>'
                                + '<a id="coolchat-chat-editor-to-service" class="coolchat-chat-editor-to" href="javascript:void(0);">对客服说</a>'
                                + '<a id="coolchat-chat-editor-to-all" class="coolchat-chat-editor-to" href="javascript:void(0);">对所有人说</a>  -->                      '
                            + '</div>'
                            + '<a class="coolchat-chat-editor-send" href="javascript:void(0);">发布</a>'
                            + '<div class="clear">&nbsp;</div>'
                        + '</div>'
                        + '<div class="coolchat-chat-editor-foot"></div>'
                    + '</div>';
                }
            });
            editor_html = $(editor_html);
            editor_html.find("img").each(changeRootPath);
            if (option.editor) {
                $(option.editor).append(editor_html);
                this.editor_container = option.editor;
            } else {
                this.container.children(".coolchat-chat-container").children(".coolchat-chat-editor-default-container").append(editor_html);
                this.editor_container = this.container.selector + ">.coolchat-chat-container>.coolchat-chat-editor-default-container";
            }
            ////////////////////////////////////////end init chat window///////////////////////////////////////////////////
            //////////////////////User Data////////////////////
            $.ajax({
                url: _this.revsv_url,
                data: "act=L&c=" + $.cookie("chatuser"),
                type: "POST",
                cache: false,
                async: false,
                dataType: "JSON",
                success: function (data, textStatus, jqXHR) {
                    _this.SrvReturnHandle(data);
                    CoolChat.alert(CoolChat.dLan.LOGIN + CoolChat.dLan.SUCCESS, {
                        Type: CoolChat.AlertOption.Type.success,
                        Position: CoolChat.AlertOption.Position.top
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    CoolChat.alert(CoolChat.dLan.LOGIN + CoolChat.dLan.FAILED + " " + textStatus + ":" + errorThrown, {
                        Position: CoolChat.AlertOption.Position.broswer
                    });
                    _this.dispose();
                }
            });
            if (!this.user || !this.user.UserName) {//login failed
                CoolChat.alert(CoolChat.dLan.LOGIN + CoolChat.dLan.FAILED, {
                    Position: CoolChat.AlertOption.Position.broswer
                });
                _this.dispose();
                return undefined;
            }
            //////////////////////end User Data////////////////////
            if (this.user.UserRole !== CoolChat.USER_ROLE.SA) {
                if(!this.isDebug)
                    $(".coolchat-chat-sa-toolbar-holder:not(.coolchat-chat-content-holder .coolchat-chat-sa-toolbar-holder)").remove();
            }
            var sendmsgtypebtn = undefined;
            if (this.user.UserRole === CoolChat.USER_ROLE.SYSUSER && this.user.SysUserType === 1) {
                var sendmsgtype = [{ Key: 1, Value: 1 }, { Key: 2, Value: 2}];
                //1: 普通消息
                //2: 行情策略
                $(".coolchat-msg-type a")[0].innerHTML = CoolChat.dLan.NORMAL_MSG;
                $(".coolchat-msg-type a")[1].innerHTML = CoolChat.dLan.KEYWORD.PLAN;
                sendmsgtypebtn = new CoolChat.RadioGroup(
                                        ".coolchat-msg-type a:not(.coolchat-chat-content-holder .coolchat-msg-type a)",
                                        sendmsgtype, "coolchat-msg-type-a-checked", "coolchat-send-method-a", "coolchat-msg-type-a-checked", undefined,
                                        ".coolchat-msg-type > span:not(.coolchat-chat-content-holder .coolchat-msg-type > span)", false);
                sendmsgtypebtn.check(0);
            } else if (this.user.UserRole === CoolChat.USER_ROLE.SYSUSER && this.user.SysUserType != 1) {
                $(".coolchat-msg-type:not(.coolchat-chat-content-holder .coolchat-msg-type)").remove();
            } else {
                $(".coolchat-msg-type:not(.coolchat-chat-content-holder .coolchat-msg-type)").remove();
            }


            var initexthtml = "<span style='color:gray;'>" + CoolChat.dLan.EDITOR_HERE + "</span>";
            function setInitText() {
                _this.editor.html(initexthtml);
            }
            function _sendMsg() {
                var _iskeywordPlan = sendmsgtypebtn && sendmsgtypebtn.getSelectValue() === 2;
                _this.editor.sync();
                var nohtml = _this.trimHTMLCode(_this.editor.html());
                if (nohtml === "" || nohtml === CoolChat.dLan.EDITOR_HERE) {
                    CoolChat.alert(CoolChat.dLan.EMPY_MSG, {
                        Type: CoolChat.AlertOption.Type.error,
                        Position: CoolChat.AlertOption.Position.top,
                        Icon_title: CoolChat.dLan.EMPY_MSG
                    });
                    CoolChat.alert(CoolChat.dLan.EMPY_MSG, {
                        Type: CoolChat.AlertOption.Type.error,
                        Position: CoolChat.AlertOption.Position.foot,
                        Icon_title: CoolChat.dLan.EMPY_MSG
                    });
                } else {
                    var touser = null;
                    var userslience = CoolChat.formatTimeString(new Date());
                    var toItem = _this.radioTo.getSelectItem();
                    var toValue = _this.radioTo.getSelectValue();
                    if ($.type(toItem) !== "undefined" && toValue !== 0) {
                        touser = new CoolChat.User(toItem.Key, "",
                            CoolChat.md5(toItem.Key + new Date().getTime()),
                            CoolChat.USER_ROLE.SYSUSER, "*", userslience);
                    } else if ($.type(_this.userRadio.getSelectItem()) !== "undefined" && _this.userRadio.getSelectValue() !== 0) {
                        //私密消息或对某某人说的消息
                        touser = new CoolChat.User(_this.userRadio.getSelectItem().Value, "",
                            CoolChat.md5(_this.userRadio.getSelectItem().Key),
                            CoolChat.USER_ROLE.GUEST, "*", userslience);
                    }
                    var _content = _this.editor.html().replace(CoolChat.dLan.EDITOR_HERE, "");
                    _this.startSend(_content, _iskeywordPlan ? CoolChat.dLan.KEYWORD.PLAN : null, touser);
                }
            }
            function setEditor(ename) {
                var editor;
                var _items = [
                            "emoticons", "|", "forecolor", "fontsize", "bold", "|", "link", "unlink"
                        ];
                switch (_this.user.UserRole) {
                    case CoolChat.USER_ROLE.GUEST:
                        _items = [
                            "emoticons", "|", "forecolor", "fontsize", "bold", "|", "link", "unlink"
                        ];
                        break;
                    case CoolChat.USER_ROLE.USER:
                        _items = [
                            "emoticons", "|", "forecolor", "fontsize", "bold", "|", "link", "unlink"
                        ];
                        break;
                    case CoolChat.USER_ROLE.SYSUSER:
                        _items = [
                            "emoticons", "image", "|", "forecolor", "fontsize", "bold", "|", "link", "unlink"
                        ];
                        break;
                    case CoolChat.USER_ROLE.SA:
                        _items = [
                            "emoticons", "image", "|", "forecolor", "fontsize", "bold", "|", "link", "unlink"
                        ];
                        break;
                }
                var k = KindEditor;
                try {
                    _this.editor = k.create(ename, {
                        resizeType: 1,
                        width: option.editorWidth ? option.editorWidth : "99.9%",
                        allowPreviewEmoticons: true,
                        allowImageUpload: _this.user.UserRole == CoolChat.USER_ROLE.GUEST
                                    || _this.user.UserRole == CoolChat.USER_ROLE.USER ? false : true,
                        allowFileManager: false,
                        items: _items,
                        themeType: option.editorTheme,
                        height: option.editorHeight
                    });
                    $(_this.editor.edit.doc).bind("click", function () {
                        if (_this.trimHTMLCode(_this.editor.html()) === CoolChat.dLan.EDITOR_HERE) {
                            _this.editor.html("");
                        }
                    });
                    $(_this.editor.edit.doc).bind("keyup", function (jqe) {
                        if ((jqe.which == 13 && !jqe.ctrlKey && !jqe.shiftKey && sendMR.getSelectValue() === 1) ||
                                ((jqe.ctrlKey && jqe.which == 13 || jqe.which == 10) && sendMR.getSelectValue() === 2)) {
                            _this.editor.html("");
                        }
                    });
                    $(document).bind("click", function () {
                        if (_this.trimHTMLCode(_this.editor.html()) === "") {
                            setInitText();
                        }
                    });
                    var sendMethod = [{ Key: 1, Value: 1 }, { Key: 2, Value: 2}];
                    var sendMR = new CoolChat.RadioGroup(
                                        ".coolchat-send-method-radios a:not(.coolchat-chat-content-holder .coolchat-send-method-radios a)",
                                        sendMethod, "coolchat-send-method-checked", "coolchat-send-method", "coolchat-send-method-checked", undefined,
                                        ".coolchat-send-method-radios > span:not(.coolchat-chat-content-holder .coolchat-send-method-radios > span)", false);
                    sendMR.changed(function (item, i) {
                        if (item.Key === 1) {//回车发送
                            $(document).unbind("keypress");
                            KindEditor(_this.editor.edit.doc).unbind();
                            $(document).keypress(function (jqe) {
                                if (jqe.which == 13) {
                                    _sendMsg();
                                }
                            });
                            KindEditor(_this.editor.edit.doc).bind("keypress", function (kevent) {
                                if (kevent.which == 13 && !kevent.shiftKey) {
                                    _sendMsg();
                                }
                            });
                        } else {//CTRL+ENTER Send Msg
                            $(document).unbind("keypress");
                            KindEditor(_this.editor.edit.doc).unbind();
                            $(document).keypress(function (jqe) {
                                if (jqe.ctrlKey && jqe.which == 13 || jqe.which == 10) {
                                    _sendMsg();
                                }
                            });
                            KindEditor(_this.editor.edit.doc).bind("keypress", function (kevent) {
                                if (kevent.ctrlKey && kevent.which == 13 || kevent.which == 10) {
                                    _sendMsg();
                                }
                            });
                        }
                        _this.PrependDebugInfo("send method: " + $.stringifyJSON(item));
                    });
                    sendMR.check(0);
                    setInitText();
                } catch (err) {
                    alert(err.message + "\r\n" + err.description + "\r\nerror num: " + err.number);
                }
            }
            setEditor(this.editor);
            $(".coolchat-chat-editor-send:not(.coolchat-chat-content-holder .coolchat-chat-editor-send)").click(function () {
                _sendMsg();
                _this.editor.html("");
            });
            $(".coolchat-chat-editor-send:not(.coolchat-chat-content-holder .coolchat-chat-editor-send)").hover(
            function () {//over
                var _smbtn = $(".coolchat-send-method-radios:not(.coolchat-chat-content-holder .coolchat-send-method-radios)");
                if (!_smbtn.is(":animated")) {
                    _smbtn.fadeIn();
                }
            },
            function () {//out
                var _smbtn = $(".coolchat-send-method-radios:not(.coolchat-chat-content-holder .coolchat-send-method-radios)");
                _smbtn.stop(true).fadeOut();
            });
            $(".coolchat-send-method-radios:not(.coolchat-chat-content-holder .coolchat-send-method-radios)").hover(
            function () {//over
                $(this).stop(true);
            }, function () {//put
                $(this).fadeOut();
            });
            function _setAlertHover() {
                //不包括 .coolchat-chat-content-holder 下的 .coolchat-chat-content-alert
                //由于 .coolchat-chat-content-holder 下的内容属于消息内容,我们不应该在除了ShowMsg之外处理它
                var topAlert = $(".coolchat-chat-content-alert-text:not(.coolchat-chat-content-holder .coolchat-chat-content-alert-text)");
                topAlert.hover(function () {
                    if (topAlert.queue().length > 0) {
                        if (topAlert.is(":animated"))//动画时隐藏
                            topAlert.hide();
                        topAlert.stop(true);
                        topAlert.fadeIn("fast");
                    }
                }, function () {
                    topAlert.fadeOut(2000);
                });

                var bottomAlert = $(".coolchat-chat-content-alert-foot-text:not(.coolchat-chat-content-holder .coolchat-chat-content-alert-foot-text)");
                bottomAlert.hover(function () {
                    if (bottomAlert.queue().length > 0) {
                        if (bottomAlert.is(":animated"))//动画时隐藏
                            bottomAlert.hide();
                        bottomAlert.stop(true);
                        bottomAlert.fadeIn("fast");
                    }
                }, function () {
                    bottomAlert.fadeOut(2000);
                });
            }
            _setAlertHover();
            ////////////////////////////////get items code//////////////////////////////////////////////////////
            function rootedItemCode(codes) {
                var tmpjq = $("<div></div>").append(codes);
                tmpjq.find("img").each(changeRootPath);
                return tmpjq.html();
            }
            $.ajax({//get user msg item html
                url: _this.userMsgItemUrl,
                type: "GET",
                cache: false,
                async: false,
                success: function (data, textStatus, jqXHR) {
                    _this.userMsgItemText = rootedItemCode(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _this.userMsgItemText = '<li id="@msg_id">'
                            + '<span class="coolchat-chat-msg-id">@msg_id</span>'
                            + '<span class="coolchat-chat-content-holder-user-fromer">@FromUserName</span>'
                            + '<span class="coolchat-chat-content-holder-to">@CHAT_TO</span>'
                            + '<span class="coolchat-chat-content-holder-sysuser-saver">@ToUserName</span>'
                            + '<span class="coolchat-chat-content-holder-saies">@CHAT_SAIES</span>'
                            + '<span class="coolchat-chat-content-holder-saywhat">@MsgContent</span>'
                            + '</li>';
                    _this.userMsgItemText = rootedItemCode(_this.userMsgItemText);
                }
            });
            $.ajax({//get system message item html
                url: _this.sysMsgItemUrl,
                type: "GET",
                cache: false,
                async: false,
                success: function (data, textStatus, jqXHR) {
                    _this.sysMsgItemText = rootedItemCode(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //if ajax error,we have a default html code. ^o^
                    _this.sysMsgItemText = '<li id="@msg_id">'
                            + '<span class="coolchat-chat-msg-id">@msg_id</span>'
                            + '<span class="coolchat-chat-content-holder-user-fromer-sysmsg">@SYSMSG</span>'
                            + '<span class="coolchat-chat-content-holder-saies">@CHAT_SAIES</span>'
                            + '<span class="coolchat-chat-content-holder-saywhat">'
                                + '<span class="coolchat-chat-content-holder-user-fromer">@ToUserName</span>'
                                + '<span class="coolchat-chat-content-holder-user-fromer-sysmsg-holder">@MsgContent</span>'
                            + '</span>'
                            + '</li>';
                    _this.sysMsgItemText = rootedItemCode(_this.sysMsgItemText);
                }
            });
            $.ajax({//get system user message item html
                url: _this.sysUserMsgItemUrl,
                type: "GET",
                cache: false,
                async: false,
                success: function (data, textStatus, jqXHR) {
                    _this.sysUserMsgItemText = rootedItemCode(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _this.sysUserMsgItemText = '<li id="@msg_id">'
                            + '<span class="coolchat-chat-msg-id">@msg_id</span>  '
                            + '<span class="coolchat-chat-content-holder-sysuser-fromer">@SysUserType-@FromUserName</span>'
                            + '<span class="coolchat-chat-content-holder-to">@CHAT_TO</span>'
                            + '<span class="coolchat-chat-content-holder-user-saver">@ToUserName</span>'
                            + '<span class="coolchat-chat-content-holder-saies">@CHAT_SAIES</span>'
                            + '<span class="coolchat-chat-content-holder-saywhat">@MsgContent</span>'
                            + '</li>';
                    _this.sysUserMsgItemText = rootedItemCode(_this.sysUserMsgItemText);
                }
            });
            $.ajax({//get keyword message item html
                url: _this.keyWordMsgItemUrl,
                type: "GET",
                cache: false,
                async: false,
                success: function (data, textStatus, jqXHR) {
                    _this.keyWordMsgItemText = rootedItemCode(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _this.keyWordMsgItemText = '<li id="@msg_id">'
                            + '<span class="coolchat-chat-msg-id">@msg_id</span>'
                            + '<span class="coolchat-chat-content-holder-sysuser-fromer">@FromUserName</span>'
                            + '<span class="coolchat-chat-content-holder-to">@KEYWORD_TO</span>'
                            + '<span class="coolchat-chat-content-holder-keyword">@KEYWORD</span>'
                            + '<span class="coolchat-chat-content-holder-saies">@KEYWORD_SAIES</span>'
                            + '<span class="coolchat-chat-content-holder-saywhat">@MsgContent</span>'
                            + '</li>';
                    _this.keyWordMsgItemText = rootedItemCode(_this.keyWordMsgItemText);
                }
            });
            $.ajax({//get online user list item html
                url: _this.UserListItemUrl.Online,
                type: "GET",
                cache: false,
                async: false,
                success: function (data, textStatus, jqXHR) {
                    _this.UserListItemText.Online = rootedItemCode(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _this.UserListItemText.Online = '<div id="@userid" class="coolchat-chat-user-list-item-hover">'
                        + '<div class="coolchat-chat-user-list-icon-holder">'
                        + '<img alt="i" src="imgs/24x24/user.png" style="position: relative;" /></div>'
                        + '<div class="coolchat-chat-user-list-username">@UserName</div>'
                        + '<a class="coolchat-chat-user-list-block-msg" title="block msgs" href="javascript:void(0);">'
                        + '<img src="imgs/16x16/block.png" title="block msgs" alt="block" /></a></div>';
                    _this.UserListItemText.Online = rootedItemCode(_this.UserListItemText.Online);
                }
            });
            $.ajax({//get online user block list item html
                url: _this.UserListItemUrl.OnlineBlock,
                type: "GET",
                cache: false,
                async: false,
                success: function (data, textStatus, jqXHR) {
                    _this.UserListItemText.OnlineBlock = rootedItemCode(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _this.UserListItemText.OnlineBlock = '<div id="@userid" class="coolchat-chat-user-list-item">'
                        + '<div class="coolchat-chat-user-list-icon-holder">' +
                            '<img id="user-icon" alt="i" src="imgs/24x24/user.png" style="position: relative;" />' +
                            '<img id="block-user" src="imgs/16x16/block.png" alt="b" style="bottom: 0px; right: 0px;' +
                                'position: absolute; z-index: 2px;" /></div>' +
                        '<div class="coolchat-chat-user-list-username">@UserName</div>' +
                        '<a class="coolchat-chat-user-list-unblock-msg" title="cancle block" href="javascript:void(0);">' +
                        '<img src="imgs/16x16/unlock.png" title="cancle block" alt="block" /></a></div>';
                    _this.UserListItemText.OnlineBlock = rootedItemCode(_this.UserListItemText.OnlineBlock);
                }
            });

            $.ajax({//get offline user list item html
                url: _this.UserListItemUrl.Offline,
                type: "GET",
                cache: false,
                async: false,
                success: function (data, textStatus, jqXHR) {
                    _this.UserListItemText.Offline = rootedItemCode(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _this.UserListItemText.Offline = '<div id="@userid" class="coolchat-chat-user-list-item">'
                        + '<div class="coolchat-chat-user-list-icon-holder">'
                            + '<img alt="i" src="imgs/24x24/useroff.png" style="position: relative;" /></div>'
                        + '<div class="coolchat-chat-user-list-username">@UserName</div>'
                        + '<a class="coolchat-chat-user-list-block-msg" title="block msgs" href="javascript:void(0);">'
                            + '<img src="imgs/16x16/block.png" title="block msgs" alt="block" /></a></div>';
                    _this.UserListItemText.Offline = rootedItemCode(_this.UserListItemText.Offline);
                }
            });
            $.ajax({//get offline user block list item html
                url: _this.UserListItemUrl.OfflineBlock,
                type: "GET",
                cache: false,
                async: false,
                success: function (data, textStatus, jqXHR) {
                    _this.UserListItemText.OfflineBlock = rootedItemCode(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _this.UserListItemText.OfflineBlock = '<div id="@userid" class="coolchat-chat-user-list-item">'
                        + '<div class="coolchat-chat-user-list-icon-holder">'
                            + '<img id="user-icon" alt="i" src="imgs/24x24/useroff.png" style="position: relative;" />'
                            + '<img id="block-user" src="imgs/16x16/block.png" alt="b" style="bottom: 0px; right: 0px;'
                                + 'position: absolute; z-index: 2px;" /></div>'
                        + '<div class="coolchat-chat-user-list-username">@UserName</div>'
                        + '<a class="coolchat-chat-user-list-unblock-msg" title="cancle block" href="javascript:void(0);">'
                            + '<img src="imgs/16x16/unlock.png" title="cancle block" alt="block" /></a></div>';
                    _this.UserListItemText.OfflineBlock = rootedItemCode(_this.UserListItemText.OfflineBlock);
                }
            });

            ////////////////////////////////get items code end//////////////////////////////////////////////////////
            var gotoend = $(".coolchat-chat-content-alert-gotoend a:not(.coolchat-chat-content-holder .coolchat-chat-content-alert-gotoend a)");
            gotoend.attr("title", CoolChat.dLan.GO_TO_END).click(function () {
                CoolChat.scrollToCurrentMsg();
            });
            var holder = $(".coolchat-chat-content-holder:not(.coolchat-chat-content-holder .coolchat-chat-content-holder)");
            var Jpreview = $(".coolchat-chat-content-holder-msg-preview:not(.coolchat-chat-content-holder ul li .coolchat-chat-content-holder-msg-preview)");
            Jpreview.attr("title", CoolChat.dLan.GO_TO_END);
            Jpreview.click(function () {
                Jpreview.stop(true);
                Jpreview.fadeOut(500).queue(function (next) {
                    $(this).scrollTop(0);
                    next();
                }).dequeue();
                CoolChat.scrollToCurrentMsg();
            });
            holder.scroll(function (e) {
                //                _this.SetDebugInfo("top:" + holder.scrollTop() + " height:" + holder.outerHeight(true)
                //                    + " ul-height:" + $(".coolchat-chat-content-holder   >ul").outerHeight(true)
                //                    + " li-height:" + $(".coolchat-chat-content-holder >ul>li").outerHeight(true)
                //                    + " li-length:" + $(".coolchat-chat-content-holder >ul>li").length
                //                    + " scrollTop: " + CoolChat.scrollLength);
                Jpreview.css("bottom", -holder.scrollTop() + "px");

            });
            try {
                $.ajax({
                    url: _this.revsv_url,
                    data: "ul=" + CoolChat.USER_OPTION.GET_SYS_USER_TYPE + "&lan=" + CoolChat.dLan.LANCODE,
                    type: "POST",
                    dataType: "json",
                    success: function (data) {
                        CoolChat.SYS_USER_TYPE = data;
                        CoolChat.SYS_USER_TYPE[0] = CoolChat.dLan.ALL_BODY;
                        CoolChat.SYS_USER_TYPE.length = CoolChat.SYS_USER_TYPE.length + 1;
                    },
                    error: function () {
                    }
                });
            } catch (err) {
            }
            ///改变背景功能
            $("#coolchat-chat-change-bg").attr("title", CoolChat.dLan.CHANGE_BG);
            $("#coolchat-chat-change-bg img").attr("alt", CoolChat.dLan.CHANGE_BG);
            $("#coolchat-chat-change-bg").click(function () {
                var url = prompt(CoolChat.dLan.INPUT_BG_URL, "");
                if (url) {
                    if (_this.isDebug) {
                        $("body").css("background-image", "url(" + url + ")");
                        $("body").css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + url + "', sizingMethod='scale')");
                    } else {
                        _this.container.children(".coolchat-chat-container").css("background-image", "url(" + url + ")");
                        _this.container.children(".coolchat-chat-container").css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + url + "', sizingMethod='scale')");
                    }
                }
            });
            ///管理用户功能
            //            $("#coolchat-chat-editor-users").attr("title", CoolChat.dLan.EDITOR_USERS);
            //            $("#coolchat-chat-editor-users img").attr("alt", CoolChat.dLan.EDITOR_USERS);
            //            $("#coolchat-chat-editor-users").click(function () {
            //                var dusers = new CoolChat.Dailog(' 输入图片地址,或者上传图片:<input /><input type="file" value="上传" />');
            //                dusers.show();
            //            });
            ///导出聊天消息功能
            $("#coolchat-chat-download-msgs").attr("title", CoolChat.dLan.DOWNLOAD_MSGS);
            $("#coolchat-chat-download-msgs img").attr("alt", CoolChat.dLan.DOWNLOAD_MSGS);
            $("#coolchat-chat-download-msgs").click(function () {
                $.download(_this.revsv_url, "act=downmsgs", "POST");
            });

            $("#coolchat-chat-delete-msgs").attr("title", CoolChat.dLan.DELETE_MSG_BTODAY);
            $("#coolchat-chat-delete-msgs img").attr("alt", CoolChat.dLan.DELETE_MSG_BTODAY);
            $("#coolchat-chat-delete-msgs").click(function () {
                $.ajax({
                    url: _this.revsv_url,
                    data: "act=deletemsgs&lan=" + CoolChat.dLan.LANCODE,
                    type: "POST",
                    dataType: "json",
                    success: function (data) {
                        if (data.count != -1) {
                            CoolChat.alert(CoolChat.dLan.WORK_SUCCESS + CoolChat.dLan.COUNT + data.count, {
                                Type: CoolChat.AlertOption.Type.success,
                                Position: CoolChat.AlertOption.Position.top,
                                Icon_title: CoolChat.dLan.WORK_SUCCESS
                            });
                        } else {
                            CoolChat.alert(CoolChat.dLan.WORK_FAILED + "," + CoolChat.dLan.NO_RIGHT, {
                                Type: CoolChat.AlertOption.Type.error,
                                Position: CoolChat.AlertOption.Position.top,
                                Icon_title: CoolChat.dLan.WORK_FAILED
                            });
                        }
                    },
                    error: function () {
                        CoolChat.alert(CoolChat.dLan.WORK_FAILED, {
                            Type: CoolChat.AlertOption.Type.error,
                            Position: CoolChat.AlertOption.Position.top,
                            Icon_title: CoolChat.dLan.WORK_FAILED
                        });
                    }
                });
            });
            var radioItemTo = [];
            for (var x = 0; x < CoolChat.SYS_USER_TYPE.length; ++x) {
                var sysusername = CoolChat.SYS_USER_TYPE[x];
                $(".coolchat-radio-buttons:not(.coolchat-chat-content-holder .coolchat-radio-buttons)").append(
                        '<a id="coolchat-chat-editor-to-' + sysusername + '" class="coolchat-chat-editor-to" href="javascript:void(0);" title="' + CoolChat.dLan.CLICK_TO_SELECT + '">' + CoolChat.dLan.CHAT_TO + sysusername + CoolChat.dLan.SAY + '</a>');
                radioItemTo.push({ Key: sysusername, Value: x });
            }
            //[{ Key: "对分析师说", Value: 0 }, { Key: "对客服说", Value: 1 }, { Key: "对所有人说", Value: 2}]
            this.radioTo = new CoolChat.RadioGroup(
                ".coolchat-radio-buttons a:not(.coolchat-chat-content-holder .coolchat-radio-buttons a)",
                radioItemTo,
                "coolchat-chat-editor-to-selected", "coolchat-chat-editor-to", "coolchat-chat-editor-to-selected",
                undefined, ".coolchat-radio-buttons > span:not(.coolchat-chat-content-holder .coolchat-radio-buttons > span)", false);
            this.radioTo.changed(function (item, i) {
                if (item && _this.userRadio && _this.userRadio.getSelectItem())
                    _this.userRadio.check(false);
                _this.PrependDebugInfo("To: " + $.stringifyJSON(item));
            });
            this.radioTo.check(radioItemTo[0]);
            //如果UserList为Radio,那么加上下面的代码
            this.userRadio = new CoolChat.RadioGroup(".coolchat-chat-user-list > div:not(.coolchat-chat-content-holder.coolchat-chat-user-list > div)",
                [], "coolchat-chat-user-list-item-selected", "coolchat-chat-user-list-item", "coolchat-chat-user-list-item-hover",
                false, undefined, false);
            this.userRadio.changing(function (item, i, cancel) {
                if (!item)
                    return;
                if (item.Key === _this.user.UserID) {
                    return false;
                }
            });
            this.userRadio.changed(function (item, i) {
                if (item && _this.radioTo)
                    _this.radioTo.check(false);
                _this.PrependDebugInfo("User: " + $.stringifyJSON(item));
            });
            this.userRadio.added(function (item, i, cancel) {
                _this.PrependDebugInfo("User Added: " + $.stringifyJSON(item));
            });
            this.userRadio.removed(function (item, i) {
                if (_this.userRadio.getLength() === 1) {
                    _this.radioTo.check(0);
                }
                _this.PrependDebugInfo("User Removed: " + $.stringifyJSON(item));
            });
            this.DebugEffect();
            //this.RevMsg("last=true",false); //装载最后一条消息
            this.RevMsg("today=true", false); //装载今日所有消息
            this.startRev();
            CoolChat.alert(CoolChat.dLan.WELCOME, {
                Type: CoolChat.AlertOption.Type.info,
                Position: CoolChat.AlertOption.Position.foot,
                Icon_title: CoolChat.dLan.WELCOME
            });
            ///end init
        },
        DebugEffect: function () {
            if (!this.isDebug) {
                $("#debug_msg_holder_bugs").remove();
                return;
            } else if ($("#debug_msg_holder_bugs").length === 0) {
                $("body").append('<div id="debug_msg_holder" title="these are debuging messages">'
                    + '<img  id="debug_msg_holder_bugs" src="' + this.rootBasePath + 'imgs/bugs/Ladybug 1.ico"/>'
                + '</div>');
            }
            var speed = 1500;
            var _this = this;
            var icons = [this.rootBasePath + "imgs/bugs/Ladybug 1.ico",
                         this.rootBasePath + "imgs/bugs/Ladybug 2.ico",
                         this.rootBasePath + "imgs/bugs/Ladybug 3.ico",
                         this.rootBasePath + "imgs/bugs/Ladybug 4.ico",
                         this.rootBasePath + "imgs/bugs/Ladybug 5.ico",
                         this.rootBasePath + "imgs/bugs/Ladybug 6.ico", ]
            $("#debug_msg_holder_bugs").fadeIn(speed).fadeOut(speed).queue(function () {
                $("#debug_msg_holder_bugs").attr("src", icons[1]);
                $(this).dequeue();
            }).fadeIn(speed).fadeOut(speed).queue(function () {
                $("#debug_msg_holder_bugs").attr("src", icons[2]);
                $(this).dequeue();
            }).fadeIn(speed).fadeOut(speed).queue(function () {
                $("#debug_msg_holder_bugs").attr("src", icons[3]);
                $(this).dequeue();
            }).fadeIn(speed).fadeOut(speed).queue(function () {
                $("#debug_msg_holder_bugs").attr("src", icons[4]);
                $(this).dequeue();
            }).fadeIn(speed).fadeOut(speed).queue(function () {
                $("#debug_msg_holder_bugs").attr("src", icons[5]);
                $(this).dequeue();
            }).fadeIn(speed).fadeOut(speed).queue(function () {
                $("#debug_msg_holder_bugs").attr("src", icons[0]);
                $(this).dequeue();
            });
            setTimeout("CoolChat.chats[" + this.index + "].DebugEffect();", 100);
        },
        SetDebugInfo: function (txt) {
            if (!this.isDebug) {
                $("#debug_msg_holder_bugs").remove();
                return;
            } else if ($("#debug_msg_holder_bugs").length === 0) {
                $("body").append('<div id="debug_msg_holder" title="these are debuging messages">'
                    + '<img  id="debug_msg_holder_bugs" src="' + this.rootBasePath + 'imgs/bugs/Ladybug 1.ico"/>'
                + '</div>');
            }
            var time = new Date();
            time = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
            $("#debug_msg_holder").html(time + " " + txt);
        },
        GetDebugInfo: function () {
            if (!this.isDebug) {
                $("#debug_msg_holder_bugs").remove();
                return;
            } else if ($("#debug_msg_holder_bugs").length === 0) {
                $("body").append('<div id="debug_msg_holder" title="these are debuging messages">'
                    + '<img  id="debug_msg_holder_bugs" src="' + this.rootBasePath + 'imgs/bugs/Ladybug 1.ico"/>'
                + '</div>');
            }
            $("#debug_msg_holder").html();
        },
        AppendDebugInfo: function (txt) {
            if (!this.isDebug) {
                $("#debug_msg_holder_bugs").remove();
                return;
            } else if ($("#debug_msg_holder_bugs").length === 0) {
                $("body").append('<div id="debug_msg_holder" title="these are debuging messages">'
                    + '<img  id="debug_msg_holder_bugs" src="' + this.rootBasePath + 'imgs/bugs/Ladybug 1.ico"/>'
                + '</div>');
            }
            var time = new Date();
            time = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
            $("#debug_msg_holder").html($("#debug_msg_holder").html() + "<div>" + time + " " + txt + "</div>");
        },
        PrependDebugInfo: function (txt) {
            if (!this.isDebug) {
                $("#debug_msg_holder_bugs").remove();
                return;
            } else if ($("#debug_msg_holder_bugs").length === 0) {
                $("body").append('<div id="debug_msg_holder" title="these are debuging messages">'
                    + '<img  id="debug_msg_holder_bugs" src="' + this.rootBasePath + 'imgs/bugs/Ladybug 1.ico"/>'
                + '</div>');
            }
            var time = new Date();
            time = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
            $("#debug_msg_holder").prepend("<div>" + time + " " + txt + "</div>");
        },
        VirtualUser: function (usernames) {//用户名使用分号隔开,或者传入数组
            var arrayuser = [];
            if (typeof usernames === "string") {
                arrayuser = usernames.split(";");
            } else if (typeof usernames === "array") {
            } else {

            }
            this.virtualCount = arrayuser.length;
            for (var i = 0; i < arrayuser.length; ++i) {
                var user = new CoolChat.User(arrayuser[i], "virtual", arrayuser[i] + i, 1, "127.0.0.1", "2013-01-01 00:00:00");
                user.IsOnline = true;
                this.addUserToUserList(user);
            }
        },
        //播放声音
        PlaySound: function (url) {
            $("#msgsound").remove();
            $(".coolchat-chat-container").append('<embed id="msgsound" src="'+url+'" autostart="true" hidden="true" loop="false">');
        },
        SrvReturnHandle: function (data, msg) {//如果处理时需要用到msg,请传入
            var _this = this;
            if (data.Silence === true) {
                if (!msg || !msg.MsgID) {
                    //                    CoolChat.alert(CoolChat.dLan.SILENCE, {
                    //                        Type: CoolChat.AlertOption.Type.error,
                    //                        Position: CoolChat.AlertOption.Position.top,
                    //                        Icon_title: CoolChat.dLan.SILENCE
                    //                    });
                } else {
                    CoolChat.alert(CoolChat.dLan.FAILED + " " + CoolChat.dLan.SILENCE, {
                        Type: CoolChat.AlertOption.Type.msgError,
                        Position: CoolChat.AlertOption.Position.msg,
                        Msg_id: "#" + msg.MsgID
                    });
                }
            }
            if (data.Alert) {
                CoolChat.alert(data.Alert.Msg, data.Alert.Option);
            }
            for (act in data.Act) {
                var i = data.Act[act];
                switch (i.Key) {
                    case CoolChat.ClientAct.ERROR:
                        CoolChat.alert(CoolChat.dLan.FAILED + i.Value, {
                            Type: CoolChat.AlertOption.Type.error,
                            Position: CoolChat.AlertOption.Position.top
                        });
                        break;
                    case CoolChat.ClientAct.MSG_SUCCESS:
                        if (_this.showMsgSuccess) {
                            CoolChat.alert(CoolChat.dLan.SUCCESS, {
                                Type: CoolChat.AlertOption.Type.msgSuccess,
                                Position: CoolChat.AlertOption.Position.msg,
                                Msg_id: "#" + msg.MsgID
                            });
                        }
                        break;
                    case CoolChat.ClientAct.MSG_FAILED:
                        CoolChat.alert(CoolChat.dLan.FAILED + i.Value, {
                            Type: CoolChat.AlertOption.Type.msgError,
                            Position: CoolChat.AlertOption.Position.msg,
                            Msg_id: "#" + msg.MsgID
                        });
                        break;
                    case CoolChat.ClientAct.RESET_USER:
                        i.Value = $.parseJSON(i.Value);
                        _this.resetUser(i.Value);
                        break;
                    case CoolChat.ClientAct.UPDATE_USER:
                        i.Value = $.parseJSON(i.Value);
                        _this.updateUser(i.Value);
                        break;
                    case CoolChat.ClientAct.REVED_MSGS:
                        i.Value = $.parseJSON(i.Value);
                        for (rm in i.Value) {
                            _this.showMsg(i.Value[rm]);
                        }
                        break;
                    case CoolChat.ClientAct.REVED_ERROE:
                        CoolChat.alert(CoolChat.dLan.REV_ERROR + i.Value, {
                            Type: CoolChat.AlertOption.Type.error,
                            Position: CoolChat.AlertOption.Position.top
                        });
                        break;
                    case CoolChat.ClientAct.LOGOFF:
                        CoolChat.alert(CoolChat.dLan.BEEN_LOGOFF, {
                            Type: CoolChat.AlertOption.Type.error,
                            Position: CoolChat.AlertOption.Position.broswer
                        });
                        _this.dispose();
                        break;
                    case CoolChat.ClientAct.USER_LIST:
                        i.Value = $.parseJSON(i.Value); //Change to Object UserListData
                        switch (i.Value.Act) {
                            case CoolChat.UserListAct.FIXED:
                                if (_this.fixedUserList) {
                                    var users = i.Value.Data;
                                    $(this.CountHolder).html(users.length+this.virtualCount);
                                    this.clearUserNotOnline(users);
                                    this.addUserNotExists(users);
                                }
                                break;
                            case CoolChat.UserListAct.OFFLINE:
                                break;
                            case CoolChat.UserListAct.NONE:
                                break;
                        }
                        break;
                }
            }
        },
        SendMsg: function (msg) {
            //msg: object CoolChat.Message
            var _this = this;
            if (!msg || typeof msg !== "object") {
                throw CoolChat.dLan.E_EMPTY_MSG;
            }
            var mjson = $.stringifyJSON(msg);
            mjson = "act=send&msg=" + encodeURIComponent(mjson);
            if (this.revJQHR) {
                try {
                    this.revJQHR.abort();
                } catch (err) {
                    if (console) {
                        console.error(err);
                    }
                }
            }
            this.sendJQHR = $.ajax({
                type: "POST",
                url: this.sendsv_url,
                data: mjson,
                cache: false,
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    _this.SrvReturnHandle(data, msg);
                    _this.startRev();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    CoolChat.alert(CoolChat.dLan.FAILED, {
                        Type: CoolChat.AlertOption.Type.msgError,
                        Position: CoolChat.AlertOption.Position.msg,
                        Msg_id: "#" + msg.MsgID
                    });
                    _this.startRev();
                }
            });
        },
        startSend: function (txt, keyword, to) {//
            if (!txt || "" === txt) {
                CoolChat.alert(CoolChat.dLan.EMPY_MSG, {
                    Type: CoolChat.AlertOption.Type.error,
                    Position: CoolChat.AlertOption.Position.top,
                    Icon_title: CoolChat.dLan.EMPY_MSG
                });
                CoolChat.alert(CoolChat.dLan.EMPY_MSG, {
                    Type: CoolChat.AlertOption.Type.error,
                    Position: CoolChat.AlertOption.Position.foot,
                    Icon_title: CoolChat.dLan.EMPY_MSG
                });
                return;
            }
            var cmsg = new CoolChat.Message();
            cmsg.MsgID = CoolChat.md5(this.user.UserID + (new Date()).getTime() + this.user.SessionId);
            cmsg.From = new CoolChat.User();
            this.user.copyTo(cmsg.From);
            cmsg.From.UserName += "(" + CoolChat.dLan.YOU + ")";
            cmsg.Content = txt;
            cmsg.Addtime = CoolChat.formatTimeString(new Date());
            cmsg.MsgTime = CoolChat.formatTimeString(new Date());
            if (keyword) {
                cmsg.Keyword = keyword;
                cmsg.Type = CoolChat.MsgType.KEYWORD;
            } else {
                cmsg.To = to;
                switch (this.user.UserRole) {
                    case CoolChat.USER_ROLE.GUEST:
                        cmsg.Type = CoolChat.MsgType.GUESTMSG;
                        break;
                    case CoolChat.USER_ROLE.USER:
                        cmsg.Type = CoolChat.MsgType.USERMSG;
                        break;
                    case CoolChat.USER_ROLE.SYSUSER:
                        cmsg.Type = CoolChat.MsgType.SYSUSERMSG;
                        break;
                    case CoolChat.USER_ROLE.SA:
                        cmsg.Type = CoolChat.MsgType.SAMSG;
                        break;
                }
            }
            this.showMsg(cmsg);
            this.SendMsg(cmsg);
        },
        showMsg: function (msg) {
            if ($(".coolchat-chat-content-holder>ul>li:not(.dialog-holder-container .coolchat-chat-content-holder>ul>li)").length > this.msgMaxItem) {
                $(".coolchat-chat-content-holder>ul>li:not(.dialog-holder-container .coolchat-chat-content-holder>ul>li)").first().remove();
            }
            var item = this.htmlMsgItem(msg);
            $(".coolchat-chat-content-holder>ul:not(.dialog-holder-container .coolchat-chat-content-holder>ul)").append(item);
            //item.fadeIn(200, function () {}); 
            //使用Item调用时, 那么这个动画效果有时会失效,这里用下面这一句来解决这个问题
            //失效原因可能是马上掉用一次showMsg() 或者 是$(".coolchat-chat-content-holder ul").append(item);还未添加完就执行了item.fadeIn(200, function () {}); 
            //已经解决,使用item.fadeIn将会失效,使用$("#" + msg.MsgID).fadeIn就可解决
            $("#" + msg.MsgID).fadeIn(500, function () {
                CoolChat.preViewOrScroll(msg.MsgID, item.html());
            });
            //CoolChat.preViewOrScroll(msg.MsgID, item.html());
        },
        htmlMsgItem: function (msg) {
            var _this = this;
            var item;
            switch (msg.Type) {
                case CoolChat.MsgType.SYSMSG:
                    item = $(this.sysMsgItemText).css("display", "none").attr("id", msg.MsgID);
                    item.children(".coolchat-chat-msg-id").html(msg.MsgID);
                    var time = CoolChat.createDate(msg.MsgTime);
                    item.children(".coolchat-chat-content-holder-msg-time").html(time.toLocaleString());
                    item.children(".coolchat-chat-content-holder-user-fromer-sysmsg").html(CoolChat.dLan.SYSMSG);
                    item.children(".coolchat-chat-content-holder-saies").html(CoolChat.dLan.CHAT_SAIES);
                    if (msg.To && msg.To.UserName) {
                        if (msg.To.UserID === this.user.UserID) {
                            item.children(".coolchat-chat-content-holder-saywhat").children(".coolchat-chat-content-holder-user-fromer").html(msg.To.UserName + "(" + CoolChat.dLan.YOU + ")");
                        } else {
                            item.children(".coolchat-chat-content-holder-saywhat").children(".coolchat-chat-content-holder-user-fromer").html(msg.To.UserName);
                        }
                    }
                    else {
                        item.children(".coolchat-chat-content-holder-saywhat").children(".coolchat-chat-content-holder-user-fromer").remove();
                    }
                    if (msg.Content == "jionchat") {
                        item.children(".coolchat-chat-content-holder-saywhat").children(".coolchat-chat-content-holder-user-fromer-sysmsg-holder").html(CoolChat.dLan.ENTER_CHAT);
                    } else if (msg.Content == "outchat") {
                        item.children(".coolchat-chat-content-holder-saywhat").children(".coolchat-chat-content-holder-user-fromer-sysmsg-holder").html(CoolChat.dLan.OUT_CHAT);
                    } else {
                        item.children(".coolchat-chat-content-holder-saywhat").children(".coolchat-chat-content-holder-user-fromer-sysmsg-holder").html(msg.Content);
                    }
                    break;
                case CoolChat.MsgType.GUESTMSG:
                case CoolChat.MsgType.USERMSG:
                    if(msg.From.UserID !== _this.user.UserID)
                        this.PlaySound(_this.MsgSoundURL);
                    item = $(this.userMsgItemText).css("display", "none").attr("id", msg.MsgID);
                    item.children(".coolchat-chat-msg-id").html(msg.MsgID);
                    var time = CoolChat.createDate(msg.MsgTime);
                    item.children(".coolchat-chat-content-holder-msg-time").html(time.toLocaleString());
                    item.children(".coolchat-chat-content-holder-user-fromer").html(msg.From.UserName);
                    if (_this.userRadio) {
                        item.children(".coolchat-chat-content-holder-user-fromer").css("cursor", "pointer");
                        item.children(".coolchat-chat-content-holder-user-fromer").click(function () {
                            var checked = _this.userRadio.check("#" + msg.From.UserID);
                            if (checked === true) {
                                CoolChat.alert(CoolChat.dLan.WORK_SUCCESS + "," + CoolChat.dLan.SELECTED + ": " + msg.From.UserName, {
                                    Type: CoolChat.AlertOption.Type.success,
                                    Position: CoolChat.AlertOption.Position.top,
                                    Icon_title: CoolChat.dLan.WORK_SUCCESS
                                });
                            } else {
                                CoolChat.alert(CoolChat.dLan.WORK_FAILED + "," + CoolChat.dLan.USER_LOGOFF + ": " + msg.From.UserName, {
                                    Type: CoolChat.AlertOption.Type.error,
                                    Position: CoolChat.AlertOption.Position.top,
                                    Icon_title: CoolChat.dLan.WORK_FAILED
                                });
                            }
                        });
                    }
                    if (msg.To && msg.To.UserName && msg.To.UserName != "*") {//如果没有接收都这里将不显示
                        item.children(".coolchat-chat-content-holder-to").html(CoolChat.dLan.CHAT_TO);
                        item.children(".coolchat-chat-content-holder-sysuser-saver").html(msg.To.UserName);
                    } else {
                        item.children().remove(".coolchat-chat-content-holder-to");
                        item.children().remove(".coolchat-chat-content-holder-sysuser-saver");
                    }
                    item.children(".coolchat-chat-content-holder-saies").html(CoolChat.dLan.CHAT_SAIES);
                    item.children(".coolchat-chat-content-holder-saywhat").html(msg.Content);
                    break;
                case CoolChat.MsgType.SYSUSERMSG:
                    item = $(this.sysUserMsgItemText).css("display", "none").attr("id", msg.MsgID);
                    item.children(".coolchat-chat-msg-id").html(msg.MsgID);
                    var time = CoolChat.createDate(msg.MsgTime);
                    item.children(".coolchat-chat-content-holder-msg-time").html(time.toLocaleString());
                    item.children(".coolchat-chat-content-holder-sysuser-fromer").html(CoolChat.SYS_USER_TYPE[msg.From.SysUserType] + "-" + msg.From.UserName);
                    if (msg.To && msg.To.UserName && msg.To.UserName != "*") {//如果没有接收都这里将不显示
                        item.children(".coolchat-chat-content-holder-to").html(CoolChat.dLan.CHAT_TO);
                        item.children(".coolchat-chat-content-holder-user-saver").html(msg.To.UserName);
                    } else {
                        item.children().remove(".coolchat-chat-content-holder-to");
                        item.children().remove(".coolchat-chat-content-holder-user-saver");
                    }
                    item.children(".coolchat-chat-content-holder-saies").html(CoolChat.dLan.CHAT_SAIES);
                    item.children(".coolchat-chat-content-holder-saywhat").html(msg.Content);
                    break;
                case CoolChat.MsgType.SAMSG:
                    item = $(this.sysUserMsgItemText).css("display", "none").attr("id", msg.MsgID);
                    item.children(".coolchat-chat-msg-id").html(msg.MsgID);
                    var time = CoolChat.createDate(msg.MsgTime);
                    item.children(".coolchat-chat-content-holder-msg-time").html(time.toLocaleString());
                    item.children(".coolchat-chat-content-holder-sysuser-fromer").html(CoolChat.dLan.SA + "-" + msg.From.UserName);
                    if (msg.To && msg.To.UserName && msg.To.UserName != "*") {//如果没有接收都这里将不显示
                        item.children(".coolchat-chat-content-holder-to").html(CoolChat.dLan.CHAT_TO);
                        item.children(".coolchat-chat-content-holder-user-saver").html(msg.To.UserName);
                    } else {
                        item.children().remove(".coolchat-chat-content-holder-to");
                        item.children().remove(".coolchat-chat-content-holder-user-saver");
                    }
                    item.children(".coolchat-chat-content-holder-saies").html(CoolChat.dLan.CHAT_SAIES);
                    item.children(".coolchat-chat-content-holder-saywhat").html(msg.Content);
                    break;
                case CoolChat.MsgType.KEYWORD:
                    item = $(this.keyWordMsgItemText).css("display", "none").attr("id", msg.MsgID);
                    item.children(".coolchat-chat-msg-id").html(msg.MsgID);
                    var time = CoolChat.createDate(msg.MsgTime);
                    item.children(".coolchat-chat-content-holder-msg-time").html(time.toLocaleString());
                    item.children(".coolchat-chat-content-holder-sysuser-fromer").html(CoolChat.SYS_USER_TYPE[msg.From.SysUserType] + "-" + msg.From.UserName);
                    item.children(".coolchat-chat-content-holder-to").html(CoolChat.dLan.KEYWORD_TO);
                    item.children(".coolchat-chat-content-holder-keyword").html(msg.Keyword);
                    item.children(".coolchat-chat-content-holder-saies").html(CoolChat.dLan.KEYWORD_SAIES);
                    item.children(".coolchat-chat-content-holder-saywhat").html(msg.Content);
                    break;
            }
            return item;
        },
        RevMsg: function (msg, longPolling) {
            var _this = this;
            function _doLongPolling(msg) {
                if (longPolling !== false) {
                    if (_this.revtimerID) {
                        clearTimeout(_this.revtimerID);
                    }
                    _this.revtimerID = setTimeout("CoolChat.chats[" + _this.index + "].beforRev();", _this.revtick);
                }
            }
            var ujson = encodeURIComponent($.stringifyJSON(this.user));
            var exmsg = "";
            if (msg) {
                exmsg = "&" + msg;
            }
            this.revJQHR = $.ajax({
                type: "POST",
                dataType: "json",
                url: this.revsv_url,
                data: "act=rev&user=" + ujson + exmsg + "&timeout=" + _this.revTimeOut,
                cahce: false,
                success: function (data, textStatus, jqXHR) {
                    _this.SrvReturnHandle(data);
                    _doLongPolling(msg);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (textStatus == "timeout") { // 请求超时
                        console.warn("rev msg timeout!");
                    }
                    if (textStatus == "abort") {
                        console.warn("rev msg aborted!");
                    } else {
                        CoolChat.alert(CoolChat.dLan.REV_ERROR, {
                            Type: CoolChat.AlertOption.Type.error,
                            Position: CoolChat.AlertOption.Position.top
                        });
                        _doLongPolling(msg);
                    }
                }
            });
        },
        startRev: function (msg) {
            //setTimeout("CoolChat.chats[" + this.index + "].beforRev(" + msg + ");", 1);
            this.isRevMsgs = true;
            this.beforRev(msg);
        },
        beforRev: function (msg) { //rev msg start here 
            //mod: 0 返回一条消息,1返回条件之前的消息,2返回条件之后的消息.
            //msgid 指定该参数将返回所有在这条消息之后的新消息.
            //msgtime 指定该参数将返回所有在这个时间之后的消息. 日期类型
            //msgaddtime 指定该参数将返回所有在这个时间之后添加的消息
            //id 指定消息记录的ID
            //使用 last=true 来返回最后一条消息
            //如果多个参数一起指定将会成 and 关系.
            ////////////////////////////////////协议暂定////////////////////////////////
            while (!this.user) {//等用户数据初始好了再开始接收
            }
            if (!this.isRevMsgs) {//未设定开始接收
                clearTimeout(this.revtimerID);
                return;
            }
            var LiID = $(".coolchat-chat-content-holder>ul>li:not(.dialog-holder-container .coolchat-chat-content-holder>ul>li)").last().attr("id");
            var where = "msgtime=" + encodeURIComponent(CoolChat.formatTimeString(new Date()));
            if (LiID)
                where = "msgid=" + LiID;
            var query = "mod=2&" + where;
            if (msg) {
                query = query + "&" + msg;
            }
            if (this.fixedUserList) {
                query = query + "&ul=" + CoolChat.USER_OPTION.GET_ONLINE_USER + "&tick=" + this.userListTick;
            }
            this.RevMsg(query);
        },
        stopRev: function () {
            this.isRevMsgs = false;
            if (this.revtimerID) {
                clearTimeout(this.revtimerID);
            }
        },
        dispose: function () {//消灭本聊天室并停止一切活动
            this.stopRev();
            this.clearUserList();
            this.stopFixedOnlineUserList();
            $(this.editor_container).html("");
            this.container.html("");

        },
        resetUser: function (_u) {
            this.user.Id = _u.Id;
            this.user.UserID = _u.UserID;
            this.user.UserIP = _u.UserIP;
            this.user.UserName = _u.UserName;
            this.user.SessionId = _u.SessionId;
            this.user.UserRole = _u.UserRole;
            this.user.SilenceExpires = _u.SilenceExpires;
            if (_u.UserRole == CoolChat.USER_ROLE.SYSUSER) {
                this.user.SysUserType = _u.SysUserType;
            }
            this.user.LastLoginTime = _u.LastLoginTime;
            this.user.AddTime = _u.AddTime;
            this.user.IsOnline = _u.IsOnline;
        },
        updateUser: function (u) {
            if (u.Id)
                this.user.Id = u.Id;
            if (u.UserName)
                this.user.UserName = u.UserName;
            if (u.SessionId)
                this.user.SessionId = u.SessionId;
            if (u.UserID)
                this.user.UserID = u.UserID;
            if (u.UserIP)
                this.user.UserIP = u.UserIP;
            if (u.UserRole)
                this.user.UserRole = u.UserRole;
            if (u.SysUserType)
                this.user.SysUserType = u.SysUserType;
            if (u.SilenceExpires)
                this.user.SilenceExpires = u.SilenceExpires;
            if (u.LastLoginTime)
                this.user.LastLoginTime = u.LastLoginTime;
            if (u.AddTime)
                this.user.AddTime = u.AddTime;
            if (u.IsOnline)
                this.user.IsOnline = u.IsOnline;
        },
        getOnlineUsers: function () {//获取在线用户名 返回数组
            var _this = this;
            var users = []//make sure it is a array;
            $.ajax({
                async: false,
                type: "POST",
                dataType: "json",
                url: this.revsv_url,
                data: "ul=" + CoolChat.USER_OPTION.GET_ONLINE_USER + "&tick=" + this.revtick,
                cahce: false,
                success: function (data, textStatus, jqXHR) {
                    if (data.Act[0].Key != CoolChat.ClientAct.USER_LIST) {//返回了错误或者需要其它操作
                        _this.SrvReturnHandle(data);
                    } else {//否则返回在线用户数组                        
                        users = $.parseJSON(data.Act[0].Value);
                        users = users.Data;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    CoolChat.alert(CoolChat.dLan.REV_ERROR, {
                        Type: CoolChat.AlertOption.Type.error,
                        Position: CoolChat.AlertOption.Position.top
                    });
                }
            });
            return users;
        },
        getOfflineUsers: function () {//获取不在线用户名 返回数组
            var _this = this;
            var users = []//make sure it is a array;
            $.ajax({
                async: false,
                type: "POST",
                dataType: "json",
                url: this.revsv_url,
                data: "ul=" + CoolChat.USER_OPTION.GET_OFFLINE_USER + "&tick=" + this.revtick,
                cahce: false,
                success: function (data, textStatus, jqXHR) {
                    if (data.Act[0].Key != CoolChat.ClientAct.USER_LIST) {//返回了错误或者需要其它操作
                        _this.SrvReturnHandle(data);
                    } else {//否则返回在线用户数组                        
                        users = $.parseJSON(data.Act[0].Value);
                        users = users.Data;
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    CoolChat.alert(CoolChat.dLan.REV_ERROR, {
                        Type: CoolChat.AlertOption.Type.error,
                        Position: CoolChat.AlertOption.Position.top
                    });
                }
            });
            return users;
        },
        exists: function (i, array) {//i 是否在 array 中
            for (var x in array) {
                if (array[x] == i)
                    return true;
            }
            return false;
        },
        clearUserNotOnline: function (users) {//删除列表中在Users中匹配不到的用户
            var _this = this;
            var items = $(".coolchat-chat-user-list > div:not(.coolchat-chat-content-holder .coolchat-chat-user-list > div)");
            items.each(function (index, domEle) {
                var tmpi = $(domEle).attr("id");
                var isit = true;
                for (var y in users) {
                    if (users[y].UserID === tmpi) {
                        isit = false;
                        break;
                    }
                }
                if (isit) {//不存在数组中
                    if ($(domEle).data("virtual") !== true) {//不是虚拟用户,则删除
                        //如果UserList是RadioButton,那么在这里加入从对象CoolChat.Radio里移除项的代码.
                        if (_this.userRadio) {
                            _this.userRadio.removeItem(tmpi, true);
                        }
                        $(domEle).remove();
                    }
                }
            });
        },
        addUserNotExists: function (users) {//将Users中没有加入列表中的用户加入列表
            var items = $(".coolchat-chat-user-list > div:not(.coolchat-chat-content-holder .coolchat-chat-user-list > div)");
            for (var x in users) {
                var uid = users[x].UserID;
                var isit = true;
                items.each(function (index, domEle) {
                    var tmpid = $(domEle).attr("id");
                    if (tmpid == uid) {
                        isit = false;
                        return false;
                    }
                });
                if (isit) {
                    this.addUserToUserList(users[x]);
                    //如果UserList是RadioButton,那么在这里加入从对象CoolChat.Radio里添加项的代码.
                    //item: {Key:users[x].UserID,Value: users[x].UserName}
                    if (this.userRadio) {
                        this.userRadio.addItem({ Key: users[x].UserID, Value: users[x].UserName }, "#" + users[x].UserID);
                    }
                }
            }
        },
        startFixedOnlineUserList: function (contain, countHolder) {
            var c = $(contain);
            if (c.children(".coolchat-chat-user-list").length != c.length) {
                c.html('<div class="coolchat-chat-user-list"></div>');
            }
            this.fixedUserList = true;
            this.CountHolder = countHolder; //设置 用户数量的元素选择器
        },
        stopFixedOnlineUserList: function () {
            this.fixedUserList = false;
            this.clearUserList();
        },
        clearUserList: function () {
            var lis = $(".coolchat-chat-user-list > div:not(.coolchat-chat-content-holder .coolchat-chat-user-list > div)");
            lis.remove();
        },
        addUserToUserList: function (user) {//向用户列表中添加用户,并添加控制方法和Hover效果
            var _this = this;
            var list = $(".coolchat-chat-user-list:not(.coolchat-chat-content-holder .coolchat-chat-user-list)");
            var block;
            var item;
            function _unblock() {
                var functhis = this;
                $.ajax({
                    url: _this.revsv_url,
                    data: "ul=" + CoolChat.USER_OPTION.UNSILENCE_USER + "&uid=" + user.UserID + "&lan=" + CoolChat.dLan.LANCODE,
                    type: "POST",
                    cache: false,
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        if (data.Silence === false) {//取消禁言成功
                            $(functhis).unbind("click");
                            $(functhis).click(_block);
                            $(functhis).attr("title", CoolChat.dLan.BLOCK_MSG);
                            $(functhis).children("img").attr("title", CoolChat.dLan.BLOCK_MSG);
                            $(functhis).children("img").attr("src", "imgs/16x16/lock.png");
                            $("#" + user.UserID).find(".coolchat-chat-user-list-icon-holder img:eq(1)").hide("fast");
                            CoolChat.alert(CoolChat.dLan.SUCCESS_UNBLOCK, {
                                Type: CoolChat.AlertOption.Type.success,
                                Position: CoolChat.AlertOption.Position.top,
                                Icon_title: CoolChat.dLan.SUCCESS_UNBLOCK
                            });
                        } else {//取消禁言失败
                            CoolChat.alert(CoolChat.dLan.FAILED_UNBLOCK, {
                                Type: CoolChat.AlertOption.Type.error,
                                Position: CoolChat.AlertOption.Position.top,
                                Icon_title: CoolChat.dLan.FAILED_UNBLOCK
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        CoolChat.alert(CoolChat.dLan.AJAX_ERROR + " " + textStatus, {
                            Type: CoolChat.AlertOption.Type.error,
                            Position: CoolChat.AlertOption.Position.top,
                            Icon_title: CoolChat.dLan.AJAX_ERROR
                        });
                    }
                });
            }
            function _block() {
                var functhis = this;
                $.ajax({
                    url: _this.revsv_url,
                    data: "ul=" + CoolChat.USER_OPTION.SILENCE_USER + "&uid=" + user.UserID + "&lan=" + CoolChat.dLan.LANCODE,
                    type: "POST",
                    cache: false,
                    dataType: "json",
                    success: function (data, textStatus, jqXHR) {
                        if (data.Silence === true) {//禁言成功
                            //更改禁言图片
                            //unbind("click");
                            //click(function(){unblock});
                            $(functhis).unbind("click");
                            $(functhis).click(_unblock);
                            $(functhis).attr("title", CoolChat.dLan.UN_BLOCK_MSG);
                            $(functhis).children("img").attr("title", CoolChat.dLan.UN_BLOCK_MSG);
                            $(functhis).children("img").attr("src", "imgs/16x16/unlock.png");
                            $("#" + user.UserID).find(".coolchat-chat-user-list-icon-holder img:eq(1)").show("fast");
                            CoolChat.alert(CoolChat.dLan.SUCCESS_BLOCK, {
                                Type: CoolChat.AlertOption.Type.success,
                                Position: CoolChat.AlertOption.Position.top,
                                Icon_title: CoolChat.dLan.SUCCESS_BLOCK
                            });
                        } else {//禁言失败
                            CoolChat.alert(CoolChat.dLan.FAILED_BLOCK, {
                                Type: CoolChat.AlertOption.Type.error,
                                Position: CoolChat.AlertOption.Position.top,
                                Icon_title: CoolChat.dLan.FAILED_BLOCK
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        CoolChat.alert(CoolChat.dLan.AJAX_ERROR, {
                            Type: CoolChat.AlertOption.Type.error,
                            Position: CoolChat.AlertOption.Position.top,
                            Icon_title: CoolChat.dLan.AJAX_ERROR
                        });
                    }
                });
            }
            var isSilence = CoolChat.createDate(user.SilenceExpires).getTime() > (new Date()).getTime();
            if (isSilence) {
                if (user.IsOnline) {
                    item = $(this.UserListItemText.OnlineBlock);
                } else {
                    item = $(this.UserListItemText.OfflineBlock);
                }
                block = item.children(".coolchat-chat-user-list-border-right ").children(".coolchat-chat-user-list-unblock-msg");
                block.attr("title", CoolChat.dLan.UN_BLOCK_MSG);
                block.children("img").attr("title", CoolChat.dLan.UN_BLOCK_MSG);
                block.click(_unblock); ////////////////////Here To Ctrl
                item.hover(
                function () {//over
                    $(this).removeClass("coolchat-chat-user-list-item").addClass("coolchat-chat-user-list-item-hover");
                    block = $(this).children(".coolchat-chat-user-list-border-right ").children(".coolchat-chat-user-list-unblock-msg");
                    if (block.is(":animated"))//动画时隐藏
                        block.hide();
                    block.stop(true);
                    block.fadeIn(500);
                },
                function () {//out
                    $(this).removeClass("coolchat-chat-user-list-item-hover").addClass("coolchat-chat-user-list-item");
                    block = $(this).children(".coolchat-chat-user-list-border-right ").children(".coolchat-chat-user-list-unblock-msg");
                    block.stop(true);
                    block.fadeOut(500);
                });
            } else {
                if (user.IsOnline) {
                    item = $(this.UserListItemText.Online);
                } else {
                    item = $(this.UserListItemText.Offline);
                }
                block = item.children(".coolchat-chat-user-list-border-right ").children(".coolchat-chat-user-list-block-msg");
                block.attr("title", CoolChat.dLan.BLOCK_MSG);
                block.children("img").attr("title", CoolChat.dLan.BLOCK_MSG);
                block.click(_block); ////////////////////Here To Ctrl
                item.hover(
                function () {//over
                    $(this).removeClass("coolchat-chat-user-list-item").addClass("coolchat-chat-user-list-item-hover");
                    block = $(this).children(".coolchat-chat-user-list-border-right ").children(".coolchat-chat-user-list-block-msg");
                    if (block.is(":animated"))//动画时隐藏
                        block.hide();
                    block.stop(true);
                    block.fadeIn(500);
                },
                function () {//out
                    $(this).removeClass("coolchat-chat-user-list-item-hover").addClass("coolchat-chat-user-list-item");
                    block = $(this).children(".coolchat-chat-user-list-border-right ").children(".coolchat-chat-user-list-block-msg");
                    block.stop(true);
                    block.fadeOut(500);
                });
            }
            if (this.user.UserRole != CoolChat.USER_ROLE.SA && (this.user.SysUserType != 1 || this.user.UserRole == CoolChat.USER_ROLE.GUEST || this.user.UserRole == CoolChat.USER_ROLE.USER)) {
                //no rights to move 调试期间请跳过权限检查
                ///debug code
                //block = undefined;
                ///debug code end
                if (block)
                    block.remove();
            }
            if (typeof user.Avatar === "string" && user.Avatar !== "") {
                var userAvatar = item.find(".coolchat-chat-user-list-icon-holder>img");
                userAvatar.attr("src", user.Avatar);
                userAvatar.bind("error", function () {
                    $(this).attr("src", "imgs/24x24/user.png");
                });
            }
            item.attr("id", user.UserID);
            var uname = user.UserName;
            if (user.UserID === this.user.UserID && user.UserRole === CoolChat.USER_ROLE.GUEST) {
                uname = "(" + CoolChat.dLan.YOU + ")" + uname;
                item.attr("title", uname);
            }
            else if (this.userRadio)
                item.attr("title", CoolChat.dLan.CLICK_TO_SELECT + " " + uname);
            else {
                item.attr("title", uname);
            }
            if (user.SessionId === "virtual") {//虚拟用户
                item.data("virtual", true);
            }
            item.children(".coolchat-chat-user-list-username").html(uname);
            list.prepend(item);
        },
        trimHTMLCode: function (html) {//去除标签,空白
            html = html.replace(/<\/?(?!img)[^>]*>/ig, ''); //去除HTML tag, 不除去IMG标签,如果一个不是IMG标签有背景无内容也将被去除
            html = html.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
            html = html.replace(/\n[\s| | ]*\r/g, '\n'); //去除多余空行
            html = html.replace(/&nbsp;/ig, ""); //去空格代码
            html = html.replace(/\s/ig, ''); //去掉空白字符
            return html;
        }
    };
    CoolChat.fn.init.prototype = CoolChat.fn;
    CoolChat.preViewOrScroll = function (msgid, html) {
        if (CoolChat.isMsgPreView()) {
            CoolChat.msgPreView(msgid, html);
        } else {
            CoolChat.scrollToCurrentMsg();
        }
    };
    CoolChat.isMsgPreView = function () {//需要预览时返回true
        var holder = $(".coolchat-chat-content-holder:not(.coolchat-chat-content-holder .coolchat-chat-content-holder)");
        var cur = holder.scrollTop();
        var min = holder.height() / 2;
        if ((CoolChat.scrollLength - min) > cur) {
            return true;
        }
        return false;

    };
    CoolChat.msgPreView = function (msgid, html) {// item Jquery Object 需要预览消息时传入 
        var lastID = $(".coolchat-chat-content-holder>ul>li:not(.dialog-holder-container .coolchat-chat-content-holder>ul>li)").last().prev().attr("id");
        if (msgid != lastID) {
            var Jpreview = $(".coolchat-chat-content-holder-msg-preview:not(.coolchat-chat-content-holder ul li .coolchat-chat-content-holder-msg-preview)");
            Jpreview.html("<ul><li>" + html + "</li></ul>");
            if (Jpreview.queue("preview").length > 0) {
                Jpreview.stop("preview", true);
                Jpreview.hide();
            }
            Jpreview.queue("preview", function (next) {
                $(this).fadeIn(1000);
                next();
            }).delay(5000, "preview").queue("preview", function (next) {
                $(this).fadeOut(200);
                next();
            }).queue("preview", function (next) {
                //preview 完成 alert("done");
                $(this).scrollTop(0);
                next();
            }).dequeue("preview");
        }
    };
    CoolChat.scrollToCurrentMsg = function () {
        var h = $(".coolchat-chat-content-holder > ul").outerHeight(true);
        var holder = $(".coolchat-chat-content-holder:not(.coolchat-chat-content-holder .coolchat-chat-content-holder)");
        holder.scrollTop(h);
        CoolChat.scrollLength = holder.scrollTop();
    };
    CoolChat.scrollGo = function (who, where) {
        //who:eny selector
        //where: number
        $(who).animate({ scrollTop: where }, 1000);
    }
    CoolChat.alert = function (msg, option) {
        //msg : to display
        //alert(msg + option.type + option.icon_url + "");
        //$(".coolchat-chat-content-alert-icon").attr("src",
        //setTimeout(toAlert(msg, option), 1); 再考虑考虑有没有这个必要 异步
        toAlert(msg, option);
        function toAlert(msg, option) {

            var icon_url;
            var icons = new CoolChat.IconUrl(CoolChat.dIconSize);
            var time = CoolChat.AlertOption.Show_time;
            if (option.Show_time) {
                time = option.Show_time;
            }
            if (option.Icon_size) {
                if (typeof option.Icon_size === "number") {
                    icons = new CoolChat.IconUrl(CoolChat.IconSize.x64);
                } else {
                    icons = new CoolChat.IconUrl(option.Icon_size);
                }
            }
            if (!option.Icon_url) {
                switch (option.Type) {
                    case CoolChat.AlertOption.Type.error:
                        icon_url = icons.Error;
                        break;
                    case CoolChat.AlertOption.Type.success:
                        icon_url = icons.Success;
                        break;
                    case CoolChat.AlertOption.Type.info:
                        icon_url = icons.Info;
                        break;
                    case CoolChat.AlertOption.Type.msgError:
                        icon_url = icons.MsgError;
                        break;
                    case CoolChat.AlertOption.Type.msgSuccess:
                        icon_url = icons.MsgSuccess;
                        break;
                }
            } else {
                icon_url = option.Icon_url;
            }
            switch (option.Position) {
                case CoolChat.AlertOption.Position.top:
                    var topAlert = $(".coolchat-chat-content-alert-text:not(.coolchat-chat-content-holder .coolchat-chat-content-alert-text)");
                    topAlert.stop(true);
                    topAlert.hide();
                    var topAlertIcon = $(".coolchat-chat-content-alert-icon:not(.coolchat-chat-content-holder .coolchat-chat-content-alert-icon)");
                    topAlertIcon.attr("src", icon_url);
                    topAlertIcon.attr("alt", "icon");
                    if (typeof option.Icon_size === "number") {
                        topAlertIcon.attr("width", option.Icon_size);
                        topAlertIcon.attr("height", option.Icon_size);
                    }
                    if (option.Icon_title) {
                        topAlertIcon.attr("title", option.Icon_title);
                    }
                    var topAlertTextHolder = $(".coolchat-chat-content-alert-text-holder:not(.coolchat-chat-content-holder .coolchat-chat-content-alert-text-holder)");
                    topAlertTextHolder.html(msg);
                    topAlert.fadeIn(CoolChat.AlertOption.Flash_time)
                    .fadeOut(CoolChat.AlertOption.Flash_time)
                    .fadeIn(CoolChat.AlertOption.Flash_time)
                    .fadeOut(CoolChat.AlertOption.Flash_time)
                    .fadeIn(CoolChat.AlertOption.Flash_time)
                    .delay(time).fadeOut(2000);
                    break;
                case CoolChat.AlertOption.Position.foot:
                    var bottomAlert = $(".coolchat-chat-content-alert-foot-text:not(.coolchat-chat-content-holder .coolchat-chat-content-alert-foot-text)");
                    bottomAlert.stop(true);
                    bottomAlert.hide();
                    var bottomAlertIcon = $(".coolchat-chat-content-alert-foot-icon:not(.coolchat-chat-content-holder .coolchat-chat-content-alert-foot-icon)");
                    bottomAlertIcon.attr("src", icon_url);
                    bottomAlertIcon.attr("alt", "icon");
                    if (typeof option.Icon_size === "number") {
                        bottomAlertIcon.attr("width", option.Icon_size);
                        bottomAlertIcon.attr("height", option.Icon_size);
                    }
                    if (option.Icon_title) {
                        bottomAlertIcon.attr("title", option.Icon_title);
                    }
                    var bottomeAlertTextHolder = $(".coolchat-chat-content-alert-foot-text-holder:not(.coolchat-chat-content-holder .coolchat-chat-content-alert-foot-text-holder)");
                    bottomeAlertTextHolder.html(msg);
                    bottomAlert.fadeIn(CoolChat.AlertOption.Flash_time)
                        .fadeOut(CoolChat.AlertOption.Flash_time)
                        .fadeIn(CoolChat.AlertOption.Flash_time)
                        .fadeOut(CoolChat.AlertOption.Flash_time)
                        .fadeIn(CoolChat.AlertOption.Flash_time)
                        .delay(time).fadeOut(2000);
                    break;
                case CoolChat.AlertOption.Position.msg:
                    var JmsgAlert = $(option.Msg_id + "> .coolchat-chat-content-holder-msg-alert");
                    var JmsgAlertIcon = $(option.Msg_id + "> .coolchat-chat-content-holder-msg-alert-icon");
                    if (option.Msg_id) {
                        if ($(option.Msg_id).length == 0) {
                            alert("CoolChat.alert: " + CoolChat.dLan.E_ALERT_MSG_ID);
                            return;
                        }
                        if (JmsgAlert.length > 0) {
                            JmsgAlert.fadeOut(2000).queue(function (next) {
                                $(this).remove();
                                next();
                            }); //由于下面的代码没有加入队列,所以在Alert完后,消息会消失
                        }
                        $(option.Msg_id).append($("<span>", {
                            "class": "coolchat-chat-content-holder-msg-alert",
                            "style": "display:none;"
                        }).append($("<img>", {
                            "class": "coolchat-chat-content-holder-msg-alert-icon",
                            src: icon_url
                        })).append($("<span>", { "class": "coolchat-chat-content-holder-msg-alert-text" }).html(msg)));

                        if (JmsgAlert.length == 0) {
                            //如果是第一次MsgAlert那么要在消息的LI加上coolchat-chat-content-holder-msg-alert后重新获取下
                            JmsgAlert = $(option.Msg_id + "> .coolchat-chat-content-holder-msg-alert");
                        }
                        if (JmsgAlertIcon.length == 0) {
                            //如果是第一次MsgAlert那么要在消息的LI加上coolchat-chat-content-holder-msg-alert后重新获取下
                            JmsgAlertIcon = $(option.Msg_id + "> .coolchat-chat-content-holder-msg-alert > .coolchat-chat-content-holder-msg-alert-icon");
                        }
                        JmsgAlertIcon.attr("alt", "icon");
                        if (option.Icon_title) {
                            JmsgAlertIcon.attr("title", option.Icon_title);
                        }
                        if (typeof option.Icon_size === "number") {
                            JmsgAlertIcon.attr("width", option.Icon_size);
                            JmsgAlertIcon.attr("height", option.Icon_size);
                        }
                        JmsgAlert.fadeIn(2000);

                    }
                    else {
                        $(".coolchat-chat-content-holder > ul > li .coolchat-chat-content-holder-msg-alert").fadeOut(2000).queue(function (next) {
                            $(this).remove();
                        });
                        $(".coolchat-chat-content-holder> ul > li").append($("<span>", {
                            "class": "coolchat-chat-content-holder-msg-alert",
                            "style": "display:none;"
                        }).append($("<img>", {
                            "class": "coolchat-chat-content-holder-msg-alert-icon",
                            src: icon_url
                        })).append($("<span>", { "class": "coolchat-chat-content-holder-msg-alert-text" }).html(msg)));
                        if (JmsgAlert.length == 0) {
                            //如果是第一次MsgAlert那么要在消息的LI加上coolchat-chat-content-holder-msg-alert后重新获取下
                            JmsgAlert = $(option.Msg_id + "> .coolchat-chat-content-holder-msg-alert");
                        }
                        if (JmsgAlertIcon.length == 0) {
                            //如果是第一次MsgAlert那么要在消息的LI加上coolchat-chat-content-holder-msg-alert后重新获取下
                            JmsgAlertIcon = $(option.Msg_id + "> .coolchat-chat-content-holder-msg-alert > .coolchat-chat-content-holder-msg-alert-icon");
                        }
                        JmsgAlertIcon.attr("alt", "icon");
                        if (option.Icon_title) {
                            JmsgAlertIcon.attr("title", option.Icon_title);
                        }
                        if (typeof option.Icon_size === "number") {
                            JmsgAlertIcon.attr("width", option.Icon_size);
                            JmsgAlertIcon.attr("height", option.Icon_size);
                        }
                        JmsgAlert.fadeIn(2000);
                    }
                    if (!CoolChat.isMsgPreView()) {
                        CoolChat.scrollToCurrentMsg();
                    }
                    break;
                case CoolChat.AlertOption.Position.broswer:
                    alert(msg);
                    break;
            }
        }
    };


    CoolChat.ready = function (option, fn) {//option为CoolChat对象,使用{ att: value } json形式传入初始值; fn 回调
        $(document).ready(function () {
            var c = new CoolChat(option);
            fn(c);
        });
    };
    CoolChat.md5 = function (str) {
        /*
        * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
        * Digest Algorithm, as defined in RFC 1321.
        * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
        * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
        * Distributed under the BSD License
        * See http://pajhome.org.uk/crypt/md5 for more info.
        */

        /*
        * Configurable variables. You may need to tweak these to be compatible with
        * the server-side, but the defaults work in most cases.
        */
        var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
        var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance   */
        var chrsz = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

        /*
        * These are the functions you'll usually want to call
        * They take string arguments and return either hex or base-64 encoded strings
        */
        function get_md5(str) {
            return hex_md5(hex_md5(str).substr(8, 14)).substr(8, 16);
        }

        function hex_md5(s) { return binl2hex(core_md5(str2binl(s), s.length * chrsz)); }
        function b64_md5(s) { return binl2b64(core_md5(str2binl(s), s.length * chrsz)); }
        function str_md5(s) { return binl2str(core_md5(str2binl(s), s.length * chrsz)); }
        function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
        function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
        function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

        /*
        * Perform a simple self-test to see if the VM is working
        */
        function md5_vm_test() {
            return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
        }

        /*
        * Calculate the MD5 of an array of little-endian words, and a bit length
        */
        function core_md5(x, len) {
            /* append padding */
            x[len >> 5] |= 0x80 << ((len) % 32);
            x[(((len + 64) >>> 9) << 4) + 14] = len;

            var a = 1732584193;
            var b = -271733879;
            var c = -1732584194;
            var d = 271733878;

            for (var i = 0; i < x.length; i += 16) {
                var olda = a;
                var oldb = b;
                var oldc = c;
                var oldd = d;

                a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
                d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
                c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
                b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
                a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
                d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
                c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
                b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
                a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
                d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
                c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
                b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
                a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
                d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
                c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
                b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);

                a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
                d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
                c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
                b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
                a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
                d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
                c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
                b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
                a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
                d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
                c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
                b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
                a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
                d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
                c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
                b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);

                a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
                d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
                c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
                b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
                a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
                d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
                c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
                b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
                a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
                d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
                c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
                b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
                a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
                d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
                c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
                b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);

                a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
                d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
                c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
                b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
                a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
                d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
                c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
                b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
                a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
                d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
                c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
                b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
                a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
                d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
                c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
                b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);

                a = safe_add(a, olda);
                b = safe_add(b, oldb);
                c = safe_add(c, oldc);
                d = safe_add(d, oldd);
            }
            return Array(a, b, c, d);

        }

        /*
        * These functions implement the four basic operations the algorithm uses.
        */
        function md5_cmn(q, a, b, x, s, t) {
            return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
        }
        function md5_ff(a, b, c, d, x, s, t) {
            return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
        }
        function md5_gg(a, b, c, d, x, s, t) {
            return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
        }
        function md5_hh(a, b, c, d, x, s, t) {
            return md5_cmn(b ^ c ^ d, a, b, x, s, t);
        }
        function md5_ii(a, b, c, d, x, s, t) {
            return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
        }

        /*
        * Calculate the HMAC-MD5, of a key and some data
        */
        function core_hmac_md5(key, data) {
            var bkey = str2binl(key);
            if (bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

            var ipad = Array(16), opad = Array(16);
            for (var i = 0; i < 16; i++) {
                ipad[i] = bkey[i] ^ 0x36363636;
                opad[i] = bkey[i] ^ 0x5C5C5C5C;
            }

            var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
            return core_md5(opad.concat(hash), 512 + 128);
        }

        /*
        * Add integers, wrapping at 2^32. This uses 16-bit operations internally
        * to work around bugs in some JS interpreters.
        */
        function safe_add(x, y) {
            var lsw = (x & 0xFFFF) + (y & 0xFFFF);
            var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
            return (msw << 16) | (lsw & 0xFFFF);
        }

        /*
        * Bitwise rotate a 32-bit number to the left.
        */
        function bit_rol(num, cnt) {
            return (num << cnt) | (num >>> (32 - cnt));
        }

        /*
        * Convert a string to an array of little-endian words
        * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
        */
        function str2binl(str) {
            var bin = Array();
            var mask = (1 << chrsz) - 1;
            for (var i = 0; i < str.length * chrsz; i += chrsz)
                bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
            return bin;
        }

        /*
        * Convert an array of little-endian words to a string
        */
        function binl2str(bin) {
            var str = "";
            var mask = (1 << chrsz) - 1;
            for (var i = 0; i < bin.length * 32; i += chrsz)
                str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask);
            return str;
        }

        /*
        * Convert an array of little-endian words to a hex string.
        */
        function binl2hex(binarray) {
            var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
            var str = "";
            for (var i = 0; i < binarray.length * 4; i++) {
                str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) +
                        hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);
            }
            return str;
        }

        /*
        * Convert an array of little-endian words to a base-64 string
        */
        function binl2b64(binarray) {
            var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            var str = "";
            for (var i = 0; i < binarray.length * 4; i += 3) {
                var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16)
                            | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8)
                            | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);
                for (var j = 0; j < 4; j++) {
                    if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
                    else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
                }
            }
            return str;
        }
        return get_md5(str);
    };
    if (typeof module === "object" && module && typeof module.exports === "object") {
        // Expose CoolChat as module.exports in loaders that implement the Node
        // module pattern (including browserify). Do not create the global, since
        // the user will be storing it themselves locally, and globals are frowned
        // upon in the Node module world.
        module.exports = CoolChat;
    } else {
        // Otherwise expose CoolChat to the global object as usual
        window.CoolChat = CoolChat;

        // Register as a named AMD module, since CoolChat can be concatenated with other
        // files that may use define, but not via a proper concatenation script that
        // understands anonymous AMD modules. A named AMD is safest and most robust
        // way to register. Lowercase jquery is used because AMD module names are
        // derived from file names, and CoolChat is normally delivered in a lowercase
        // file name. Do this after creating the global so that if an AMD module wants
        // to call noConflict to hide this version of CoolChat, it will work.
        if (typeof define === "function" && define.amd) {
            define("coolchat", [], function () { return CoolChat; });
        }
    }

})(window); 